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 效果图如下
欢迎转载,但请注明出处:http://www.VEVb.com/julyweb/,谢谢!新闻热点
疑难解答