1.1 本文只显示需要修改配置的操作,初次引入log4net环境的请参考上文。
1.2 安装mysql-connector-net.msi环境,下载地址。并手动生成数据库日志信息表。
2.1 修改log4net.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <log4net> <!-- Mysql日志类 --> <logger name="logdb"> <level value="ALL" /> <appender-ref ref="AdoNetAppender_Mysql" /> </logger> <!-- Mysql日志附加介质 --> <appender name="AdoNetAppender_Mysql" type="log4net.Appender.AdoNetAppender"> <!-- 日志信息缓冲区大小,测试时为0,实际部署可适当改为100 --> <bufferSize value="0" /> <!-- mysql-connector-net版本为6.8.3以上,不需更改数据源 --> <ConnectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/> <!-- 数据库连接字符串 --> <ConnectionString value="server=localhost;user id=root;password=root;persist security info=True;character set=utf8;database=test;pooling=true;"/> <!-- 数据库日志插入命令 --> <commandText value="INSERT INTO loginfo (DateTime,Message,UserId) VALUES (@log_date, @message, @user_id)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <!-- 格式带property为自定义信息 --> <parameter> <parameterName value="@user_id" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{UserId}" /> </layout> </parameter> </appender> </log4net> </configuration>
3.1 修改工具类LogHelper
namespace July.Demo.Win { public class LogHelper { static readonly log4net.ILog logdb = log4net.LogManager.GetLogger("logdb"); public static void WriteLog(string info) { if (logdb.IsInfoEnabled) { //使用线程相关属性设定自定义信息 log4net.ThreadContext.Properties["UserId"] = "U-1001"; logdb.Info(info); } } } }
4.1 效果图如下
QQO6/fHkVi5zVJW5ZxzRLI00E764h0RICbYSDYE9SDE8MxmwC+OYiiKOr0i8ebT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