最近由Winform转为WPF,日志记录采用Log4Net机制,具体操作为下:
#1 下载log4net.dll,
具体方法为从工具栏进入Nuget包管理器,直接输入Log4net进行下载安装即可;
#2 下载好后,在App.config进行配置,节点配置如下
```
<configSections>
<!--log4net配置-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
```
#3 具体数据库和TXt文档配置
```
<log4net >
<appender name="DefaultFileAppender" type="log4net.Appender.RollingFileAppender">
<LockingModel value="log4net.Appender.FileAppender.MinimalLock" />
<file value="logfile\"/>
<appendToFile value="true"/>
<maxSizeRollBackups value="180"/>
<maximumFileSize value="1MB"/>
<rollingStyle value="Date"/>
<datePattern value='yyyy-MM-dd/"Log.txt"' />
<staticLogFileName value="false"/>
<!--定义文件存放位置-->
<!--file value="D://logfile.txt"/-->
<!--放在Debug下-->
<!--file value="log//logfile.txt"/-->
<layout type="log4net.Layout.PatternLayout">
<!--输出格式-->
<!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="记录时间:%date 日志级别:%-5level - 描述:%message%newline"/>
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="Data source = EDP-IR137\sqlexpress; initial catalog=i-Reader_X;integrated security = true" />
<commandText value="INSERT INTO Log([LogDate],[Level],[Message],[Exception]) VALUES (@log_date, @log_level, @message, @exception)"/>
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
<!--layout type="log4net.Layout.PatternLayout" value="%date"/-->
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="DefaultFileAppender"/>
<appender-ref ref= "AdoNetAppender"/>
</root>
</log4net>
```
#4 新建类,写入一个 静态变量
```
class Logfornet
{
public static ILog Log { get; } = LogManager.GetLogger("Log");
}
```
#5 property里一定要加这句
```
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
```
#6 使用方法
```
Logfornet.Log.Info("00用户登录");
```