Arto said:
Would it be possible to use C# 3.0 runtime macros to do following:
If Apache's log4net is loaded, calls like
log.DebugFormat("Hello {0}","world");
generate the logging, but if the dll is not loaded, nothing happens?
(I like to make program so, that the if the dll is missing, it works
but without the logging)
I believe you will need to use reflection to accomplish that.
See example below.
Note that reflection carry a certain overhead.
Arne
====================================================
using System;
using System.IO;
using System.Reflection;
//using log4net;
//using log4net.Config;
namespace E
{
public class OptionalLog4netLogger
{
private Assembly asm;
private object il;
private MethodInfo mi;
public OptionalLog4netLogger(string name)
{
try
{
asm = Assembly.LoadFrom(@"C:\log4net.dll");
Type xc = asm.GetType("log4net.Config.XmlConfigurator",
false, false);
xc.InvokeMember("Configure", BindingFlags.DeclaredOnly
| BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod,
null, null, null);
Type lm = asm.GetType("log4net.LogManager", false, false);
il = lm.InvokeMember("GetLogger",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static |
BindingFlags.InvokeMethod, null, null, new object[] { name });
mi = il.GetType().GetMethod("DebugFormat",
BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance,
null, new Type[] { typeof(String), typeof(object[]) }, null);
}
catch(FileNotFoundException)
{
asm = null;
}
}
public void DebugFormat(string fmt, params object[] args)
{
if(asm != null)
{
mi.Invoke(il, new object[] { fmt, args});
}
}
}
public class Test
{
public static void Main(string[] args)
{
OptionalLog4netLogger log = new OptionalLog4netLogger("Test");
//XmlConfigurator.Configure();
//ILog log = LogManager.GetLogger("Test");
log.DebugFormat("This is just a {0} test", "little");
}
}
}