简体   繁体   中英

Unable to create Logging file using Log4Net in C#

I am trying to write a log file using Log4net in C# but the log is getting printed on console. Here is my code

 class Program
{
    public static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    static void Main(string[] args)
    {
        log4net.Config.BasicConfigurator.Configure();
        Log.Debug("TEST");
        Console.Read();
    }
}

Here is the XML (log4net.config)

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender type="log4net.Appender.RollingFileAppender" name="RollingFileAppender">
    <file value="mylog.txt"/>
    <appendToFile value="true"/>
    <datePattern value="yyyyMMdd"/>
    <rollingStyle value="Once"/>

    <layout type="log4net.Layout.SimpleLayout">
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingFileAppender"/>    
  </root>
</log4net>

inside Assembly.cs i have

[assembly: XmlConfigurator(Watch=true)]

But still the log file isn't create inside debug folder. Does anyone have any idea why this is getting printed on console instead of inside the Log file.

Do you copy the config file to the output directory?

If you are using Visual Studio, set the Build Action to Copy to output directory="Copy Always" or "Copy if newer" and BuildAction="Content"

If you are using the app.config for log4net configuration, I think you should use

log4net.Config.XmlConfigurator.Configure();

Also, you might need to resolve the log after calling configure

public static log4net.ILog Log { get; private set; }

static void Main(string[] args)
{
    log4net.Config.XmlConfigurator.Configure();
    Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM