今天要求做个log4net自定义字段到数据库,在网上找了好多例子,都运行不成功。最后找了个国外的,很简单的就解决了。 log4net它已经定义的字段有 <commandText value="INSERT INTO xiao_log(Date,Thread,Level,Logger,Message)VALUES(@log_date, @thread, @log_level, @logger, @message)"/> 中的Date,Thread,Level,Logger,Message这个5个。 现在自定义2个字段 <commandText value="INSERT INTO xiao_log(Date,Thread,Level,Logger,Message,UserId,UserName)VALUES(@log_date, @thread, @log_level, @logger, @message,@userid,@username)"/>
自定义字段参数声明和原有参数声明的区别 <--原有字段--> <parameter> <parameterName value="@log_level"/> <dbType value="String"/> <size value="50"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level"/> </layout> </parameter> <parameter> <parameterName value="@logger"/> <dbType value="String"/> <size value="255"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger"/> </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="@userid"/> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{userid}" /> </layout> </parameter> <parameter> <parameterName value="@username"/> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{username}" /> </layout> </parameter>
最后加上这两句话,把参数替换掉就好了 log4net.GlobalContext.Properties["userid"] = "23"; log4net.GlobalContext.Properties["username"] = "dongsheng"; Log.Info(ex,"23434");