Invoking a method from class library containing code to log messages using Log4Net, using reflection, log file is not created

  • Thread starter Thread starter Raghunathan S
  • Start date Start date
R

Raghunathan S

Guest
Hi All,

I am trying to invoke a method which is defined inside a Class Library, using Reflection.

Method defined in the Class Library (DynamicLogger) contains some logic along with code to Log the messages using Log4Net.

Method (GetDetails) call succeeds without any errors, but the Logging never happens, log file is not created. There is no error or exceptions while initialising the logger (InitLogger) from code.

Sample Application which invokes the Class Library is a Windows Form Application, here is the invocation code:

private void button1_Click(object sender, EventArgs e)
{
string dllFilePath = @"E:\Raghunathan\Works\DynamicLogger\bin\Debug\DynamicLogger.dll";

MakeReflectionCall(dllFilePath);
}

static void MakeReflectionCall(string path)
{
Assembly asm = Assembly.LoadFrom(path);

if (asm != null)
{
string className = "DynamicLogger.MyClass";

Type t = asm.GetType(className);

MethodInfo method = t.GetMethod("GetDetails");

if (method != null)
{
object refObjectInst = Activator.CreateInstance(t);

var result = method.Invoke(refObjectInst, null);

}
}
}

Code for the Class Library Class

using System;
using System.IO;
using System.Reflection;

namespace DynamicLogger
{
public class MyClass
{
string ConfigFilePath
{
get
{
return Path.Combine(AsmFolderPath, "DynamicLogger.dll.config");
}
}
string AsmFilePath
{
get
{
return Assembly.GetExecutingAssembly().Location;
}
}

string AsmFolderPath
{
get
{
return System.IO.Path.GetDirectoryName(AsmFilePath);
}
}

public MyClass()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllFileName = args.Name.Remove(args.Name.IndexOf(',')) + ".dll";

if (dllFileName.Trim().ToLower().IndexOf(".resources") > 0)
return null;

string dllPath = Path.Combine(AsmFolderPath, "lib", dllFileName);

return Assembly.LoadFile(dllPath);
}

private void InitLogger()
{
if (File.Exists(ConfigFilePath))
Log.InitLogger(GetType(), ConfigFilePath);
else
Log.InitLogger(GetType());
}

public string GetDetails()
{
string details = "";

InitLogger();

try
{
Log.LogMessage(LogLevel.INFO, "GetDetail: Method Invoked");

/*
* Logic to get some details from the database goes here
*/

Log.LogMessage(LogLevel.INFO, "GetDetail: Details retried from the DB successfully");
}
catch(Exception ex)
{
Log.LogException(ex);
}

Log.LogMessage(LogLevel.INFO, "GetDetail: Method Completed Successfully");

return details;
}
}
}

Code for Log4Net Wrapper Class (Log)

using log4net;
using log4net.Config;
using System;
using System.Text;

namespace DynamicLogger
{
public enum LogLevel
{
INFO = 0,
WARN,
ERROR,
FATAL,
DEBUG
}

public static class Log
{
private static ILog logger = null;

public static void InitLogger (System.Type type)
{
XmlConfigurator.Configure();
logger = LogManager.GetLogger(type);
}

public static void InitLogger(System.Type type, string logConfigFilePath)
{

if (System.IO.File.Exists(logConfigFilePath))
{
XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(logConfigFilePath));
logger = LogManager.GetLogger(type);
}
}

public static void LogMessage(LogLevel level, string message)
{
if (logger == null)
return;

switch (level)
{
case LogLevel.INFO:
logger.Info(message);
break;
case LogLevel.WARN:
logger.Warn(message);
break;
case LogLevel.FATAL:
logger.Fatal(message);
break;
case LogLevel.ERROR:
logger.Error(message);
break;
case LogLevel.DEBUG:
logger.Debug(message);
break;
}
}

public static void LogException(Exception ex)
{
if (logger == null)
return;

StringBuilder sbException = new StringBuilder();

if (ex != null)
{
GetExceptionDetails(ex, sbException, 0);

if (ex.InnerException != null)
GetInnerExceptionDetails(ex.InnerException, sbException, 1);

logger.Fatal(sbException.ToString());
}
}

private static void GetExceptionDetails(Exception ex, StringBuilder sbException, int level)
{
if (level == 0)
sbException.Append("\r\nException:\n");
else
sbException.Append("\r\nException Level " + level + ":\n");

sbException.Append("Message: " + ex.Message + "\n");
sbException.Append("Source: " + ex.Source + "\n");
sbException.Append("TargetSite: " + ex.TargetSite + "\n");
sbException.Append("StackTrace: " + ex.StackTrace + "\n");
if (ex.Data != null && ex.Data.Count > 0)
{
sbException.Append("\r\nData:\r\n");
foreach (string dataKey in ex.Data.Keys)
{
sbException.Append(dataKey + ": " + ex.Data[dataKey] + "\n");
}
}
}

private static void GetInnerExceptionDetails(Exception ex, StringBuilder sbException, int level)
{
GetExceptionDetails(ex, sbException, level);
if (ex.InnerException != null)
{
GetInnerExceptionDetails(ex.InnerException, sbException, (level + 1));
}
}
}
}
App.Config file in the DynamicLogger Class Library Project

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="lib"/>
</assemblyBinding>
</runtime>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="../Logs/%date{yyyy-MMM-dd}.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>


Any help is really appreciated.

Thanks.

Raghunathan S

Continue reading...
 
Back
Top