0

I am trying to insert in my log lines the location of where a certain event occurred, I have tried several solutions so far but none have worked for me and I don't understand why. I know it must be a silly problem but I haven't found something that would solve it.

I am using the log4net library and these are the results I have had so far:

public class Logger : ILogger
{
    private readonly ILog _logger;

    public Logger()
    {
        this._logger = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);
    }

    public void Debug(string message)
    {
        this._logger?.Debug(message);
    }

    public void Info(string message)
    {
        this._logger?.Info(message);
    }

    public void Error(string message, Exception? ex = null)
    {
        this._logger?.Error(message, ex?.InnerException);
    }

    public void Warning(string message)
    {
        this._logger?.Warn(message);
    }
}

The ILogger interface is my creation as an abstraction to be able to change the log library without problems, the ILog type variable is used by log4net.

And this is what is coming out of my console now, without the naming of the class/method:

2022-11-08 10:02:41,161 WARN : Disconnected from the MQTT broker

2022-11-08 10:02:41,161 ERROR: Failed to connect to the MQTT broker

And this is my log4net.config:

<configuration>
<log4net>
    <appender name="Console" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%-4thread] %-5level %logger [%M %C] - %message%newline" />
        </layout>
    </appender>

    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="Log.txt" />
        <appendToFile value="false" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="50MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%-4thread] %-5level %logger [%M %C] - %message%newline" />
        </layout>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="Console" />
        <appender-ref ref="RollingFileAppender" />
    </root>
</log4net>
fuba
  • 23
  • 5
  • 1
    You can get line number, member name and file path using CompilerServices, see [this answer](https://stackoverflow.com/a/14122771/552510). You can't get full stack trace through these though – Jonathan Nov 08 '22 at 13:25

1 Answers1

1

you can get the class and method info like this and use it according to when writing to logs.

string className = this.GetType().Name;
string classNameInStaticMethod = typeof(Program).Name; //this could be your class name
string strMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197