3

I have created log4net wrapper class as follow

public class Logger : ILogger
{

    private log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(Logger));


    public void MyMethod(object message, params object[] args)
    {
        if (args.Length == 0 || args == null)
        {
            _logger.Info(message);
        }
        else
        {
            _logger.InfoFormat(message.ToString(), args);
        }
    }
 }

I call wrapper method in my controller class

   Logger obj=new Logger(); 
   obj.MyMethod("Constructor of AccountController class called.");

I have define layout pattern in webconfig as

<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="C:\Log\My.log" />
      <param name="AppendToFile" value="true"/>     
      <maximumFileSize value="500KB" />
      <maxSizeRollBackups value="2" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date,%file(%line), [%-5level],%message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="RollingFile" />
    </root>
  </log4net>

As per the pattern I am expecting following log

2016-07-27 10:12:48,480,e:\MyProject\Controllers\AccountController.cs(24), [INFO ],Constructor of AccountController class called.

But I am getting

2016-07-27 10:12:48,480,e:\MyProject\Infrastructure\Utilities\Logger.cs(15), [INFO ],Constructor of AccountController class called.

Filename and linenumber both I am getting wrong.What I am missing.

Maverick
  • 1,396
  • 5
  • 22
  • 42

2 Answers2

0

As far as I know c# is not like c/c++, it's different to get filename and linenumber. Maybe its implemention is the following codes:

string currentFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); 
int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();

So, the result is not what you expecte.

Also see Print the source filename and linenumber in C#

Community
  • 1
  • 1
samm
  • 620
  • 10
  • 22
  • Thanks for reply this I also can do by new StackFrame(0, true); My main concern is how I pass this information to log4net Info or InfoFormat method without making change in PatternLayout – Prashant Desai Jul 27 '16 at 09:29
0

You will find what you need in this answer: https://stackoverflow.com/a/3448439/106567.

The key is not to use the ILog interface in your wrapper. Instead you need to use the Logger class which you can call like this:

_logger.Log(MyLogWrapper.ThisDeclaringType, log4netLevel, message, ex);

The important part is the first parameter which lets log4net remove the unwanted parts of the stacktrace when accessing things like method name or file name. It requires a bit more work to write your wrapper this way, but you can get exactly the result you want.

Community
  • 1
  • 1
Stefan Egli
  • 17,398
  • 3
  • 54
  • 75