简体   繁体   English

最小的log4net配置

[英]Minimal log4net configuration

How to configure a .NET console application to use a rolling log file and be able to clear its contents when the application is running? 如何配置.NET控制台应用程序以使用滚动日志文件并能够在应用程序运行时清除其内容?

I am answering my own question after having gathered all the needed pieces by searching the web and going through the log4net documentation (which is quite chatty) once again. 在通过搜索网络并再次浏览log4net文档(相当闲谈)收集了所有必要的内容之后,我正在回答自己的问题。 I tend to do this same job once in a year or two because surprisingly there is still no single answer covering all the requirements existing on SO. 我倾向于每隔一两年执行一次相同的工作,因为令人惊讶的是,仍然没有一个单一的答案可以涵盖SO上的所有需求。

a) install NuGet package log4net (currently 2.0.x) a)安装NuGet软件包log4net(当前是2.0.x)

b) add the following line to the beginning of the Start method b)将以下行添加到Start方法的开头

public static void Start(string[] args)
{
    log4net.Config.XmlConfigurator.Configure();
    ...
}

c) add the following sections to App.config c)将以下部分添加到App.config中

*log4net sdk documentation is quite useful when trying to figure out the meaning of all these configuration values * log4net sdk文档在试图弄清所有这些配置值的含义时非常有用

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>
    <log4net>
        <appender name="RollingFileAppender_All" type="log4net.Appender.RollingFileAppender">
            <file value="MyApplication.log" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="1MB" />
            <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger - %message %exception%newline" />
            </layout>
        </appender>
        <root>
            <level value="ALL" /> <!-- ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF -->
            <appender-ref ref="RollingFileAppender_All" />
        </root>
    </log4net>
</configuration>

d) create a logger instance and use it d)创建一个记录器实例并使用它

using log4net;

public class SomeClass
{
    private static readonly ILog log = LogManager.GetLogger(typeof(SomeClass));

    public void DoSomething()
    {
        try
        {
            throw new InvalidOperationException("test");
        }
        catch (Exception ex)
        {
            log.Error(ex);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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