1.去nuget搜索Log4net并安装。
2.在app.config中添加配置文件
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<!--log4net配置start-->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="ALL" />
</root>
<logger name="OperationLogger" additivity="false">
<level value="ALL" />
<appender-ref ref="FileAppender" />
<appender-ref ref="UDPAppender" />
</logger>
<logger name="AlarmLogger" additivity="false">
<level value="ALL" />
<appender-ref ref="Alarm2FileAppender" />
</logger>
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:/Logs/AheadLog.txt" />
<appendToFile value="true" />
<Encoding value="utf-8" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Composite" /><!--Composite是Date+Size的意思-->
<DatePattern value="yyyyMMdd'.txt'"></DatePattern>
<maxSizeRollBackups value="1" /><!--每天最多2个备份文件--><!--比如只保留30天的log文件,必须用代码删除-->
<maximumFileSize value="15MB" /><!--每个文件最大15兆-->>
<staticLogFileName value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy-MM-dd|HH:mm:ss.fff}|%-5level|%message%newline" />
</layout>
</appender>
<appender name="UDPAppender" type="log4net.Appender.UdpAppender">
<remoteAddress value="127.0.0.1" />
<remotePort value="7171" />
<Encoding value="utf-8" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%date{(MM/dd HH:mm:ss.fff)}|%level|%message%newline" />
</layout>
</appender>
<appender name="Alarm2FileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:/LogAlarm/alarm.txt" />
<appendToFile value="true" />
<Encoding value="utf-8" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<rollingStyle value="Composite" /><!--Composite是Date+Size的意思-->
<DatePattern value="yyyyMMdd'.txt'"></DatePattern>
<maxSizeRollBackups value="1" /><!--每天最多2个备份文件--><!--比如只保留30天的log文件,必须用代码删除-->
<maximumFileSize value="15MB" /><!--每个文件最大15兆-->>
<staticLogFileName value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{yyyy-MM-dd|HH:mm:ss.fff}|%-5level|%message%newline" />
</layout>
</appender>
</log4net>
</configuration>
3.在properties中的AssemblyInfo文件内添加下列代码
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", ConfigFileExtension = "config", Watch = true)]
注意这里最好指定一下ConfigFile=“配置文件名称”,因为原来我没有加这一句导致日志一直记录不上
4.初始化并使用日志记录
public partial class MainWindow: Window
{
public static log4net.ILog operationLog = log4net.LogManager.GetLogger("OperationLogger");
public MainWindow()
{
InitializeComponent();
operationLog.Info("启动");
}
}
至此,每当调用operationLog.Info("");时,都会把日志写入日志文件。