log4net 发布到生产环境不写日志的解决方法

Posted 漂泊雪狼的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了log4net 发布到生产环境不写日志的解决方法相关的知识,希望对你有一定的参考价值。

1、升级到log4net的最新版

PM下执行

Install-Package log4net

还是无法解决的,使用下面的方法

2、使用Nlog替换之,详见https://github.com/NLog/NLog/wiki/Tutorial

 安装

Install-Package NLog.Config 

 

NLog使用方法比log4net更为简单,配置文件如下,如果成windows程序需将NLog.config自动复制到bin下面

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
 5       autoReload="true"
 6       throwExceptions="false"
 7       internalLogLevel="Off" internalLogFile="F:\\temp\\20160907\\NLog\\log\\nlog-internal.log">
 8 
 9   <!-- optional, add some variables
10   https://github.com/nlog/NLog/wiki/Configuration-file#variables
11   -->
12   <variable name="myvar" value="myvalue"/>
13 
14   <!--
15   See https://github.com/nlog/nlog/wiki/Configuration-file
16   for information on customizing logging rules and outputs.
17    -->
18   <targets>
19 
20     <!--
21     add your targets here
22     See https://github.com/nlog/NLog/wiki/Targets for possible targets.
23     See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
24     -->
25 
26     <!--
27     Write events to a file with the date in the filename.
28     <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
29             layout="${longdate} ${uppercase:${level}} ${message}" />
30     -->
31       <target name="logfile" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" />
32       <target name="console" xsi:type="ColoredConsole" />
33   </targets>
34 
35   <rules>
36       <!-- add your logging rules here -->
37 
38       <!--
39     Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
40     <logger name="*" minlevel="Debug" writeTo="f" />
41     -->
42       <logger name="*" minlevel="Debug" writeTo="logfile" />
43       <logger name="*" minlevel="Info" writeTo="console" />
44   </rules>
45 </nlog>
NLog.config

调用代码:

 1   Logger logger = LogManager.GetCurrentClassLogger();
 2 
 3 
 4             logger.Trace("Sample trace message");
 5             logger.Debug("Sample debug message");
 6             logger.Info("Sample informational message");
 7             logger.Warn("Sample warning message");
 8             logger.Error("Sample error message");
 9             logger.Fatal("Sample fatal error message");
10 
11 
12             logger.Info("wilson测试 日志日期:{0}", DateTime.Now);

执行结果,非常漂亮的控制台输出:

 

web站点配置log写入到sql server数据库,需要安装NLog.Web

Install-Package NLog.Web

配置文件如下

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
 3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4       xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
 5       autoReload="true"
 6       throwExceptions="false"
 7       internalLogLevel="Off" internalLogFile="F:\\temp\\20160907\\NLog\\log\\nlog-internal.log">
 8 
 9   <!-- optional, add some variables
10   https://github.com/nlog/NLog/wiki/Configuration-file#variables
11   -->
12   <variable name="myvar" value="myvalue"/>
13 
14   <!--
15   See https://github.com/nlog/nlog/wiki/Configuration-file
16   for information on customizing logging rules and outputs.
17    -->
18   <targets>
19 
20     <!--
21     add your targets here
22     See https://github.com/nlog/NLog/wiki/Targets for possible targets.
23     See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
24     -->
25 
26     <!--
27     Write events to a file with the date in the filename.
28     <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
29             layout="${longdate} ${uppercase:${level}} ${message}" />
30     -->
31       <target name="logfile" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" />
32       <target name="console" xsi:type="ColoredConsole" />
33 
34       <target name="db"
35       xsi:type="Database"
36       connectionStringName="NLogConn"
37       commandType="StoredProcedure"
38       commandText="[dbo].[NLog_AddEntry_p]"
39         >
40           <parameter name="@machineName"    layout="${machinename}" />
41           <parameter name="@siteName"       layout="${iis-site-name}" />
42           <parameter name="@logged"         layout="${date}" />
43           <parameter name="@level"          layout="${level}" />
44           <parameter name="@username"       layout="${aspnet-user-identity}" />
45           <parameter name="@message"        layout="${message}" />
46           <parameter name="@logger"         layout="${logger}" />
47           <parameter name="@properties"     layout="${all-event-properties:separator=|}" />
48           <parameter name="@serverName"     layout="${aspnet-request:serverVariable=SERVER_NAME}" />
49           <parameter name="@port"           layout="${aspnet-request:serverVariable=SERVER_PORT}" />
50           <parameter name="@url"            layout="${aspnet-request:serverVariable=HTTP_URL}" />
51           <parameter name="@https"          layout="${when:inner=1:when=\'${aspnet-request:serverVariable=HTTPS}\' == \'on\'}${when:inner=0:when=\'${aspnet-request:serverVariable=HTTPS}\' != \'on\'}" />
52           <parameter name="@serverAddress"  layout="${aspnet-request:serverVariable=LOCAL_ADDR}" />
53           <parameter name="@remoteAddress"  layout="${aspnet-request:serverVariable=REMOTE_ADDR}:${aspnet-request:serverVariable=REMOTE_PORT}" />
54           <parameter name="@callSite"       layout="${callsite}" />
55           <parameter name="@exception"      layout="${exception:tostring}" />
56       </target>
57 
58 
59   </targets>
60 
61   <rules>
62       <!-- add your logging rules here -->
63 
64       <!--
65     Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
66     <logger name="*" minlevel="Debug" writeTo="f" />
67     -->
68       <logger name="*" minlevel="Debug" writeTo="logfile" />
69       <logger name="*" minlevel="Info" writeTo="console" />
70 
71       <logger name="*" minlevel="Debug" writeTo="db" />
72   </rules>
73 </nlog>
Web NLog配置

 

Web.Config要加上对应数据库连接

<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
        <add name="NLogConn" connectionString="Server=.;uid=sa;pwd=sa;Database=db;"/>
    </connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>

</configuration>

保存数据库结果:

写入oracle的配置,使用System.Data.OracleClient,.net 4.0以上已经抛弃

 1 <targets>
 2   <target name="oraclelog" type="Database">
 3 
 4           <dbProvider>System.Data.OracleClient.OracleConnection,System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</dbProvider>
 5 
 6           <connectionString>Data Source=JMDB_215;User ID=TYUM_UM; Password=DEV_TYUM_UM;</connectionString>
 7 
 8           <commandText>insert into RS_LOGTABLE (log_user,log_level,log_date,log_message) values(:log_user,:log_level,:log_date,:log_message)</commandText>
 9 
10           <parameter name=":log_user" layout="${aspnet-user-identity}"/>
11           <parameter name=":log_level" layout="${level}"/>
12           <parameter name=":log_date" layout="${date}"/>
13           <parameter name=":log_message" layout="${message}"/>
14 
15       </target>
16 </targets>
17  <rules>
18     <logger name="*" minlevel="Debug" writeTo="oraclelog" />
19 </rules>

 写入oracle的配置,使用Oracle.DataAccess.Client,配置文件如下:

 1     <targets>
 2   <target name="oraclelog" type="Database">
 3 
 4           <!--<dbProvider>Oracle.ManagedDataAccess.Client,Oracle.ManagedDataAccess</dbProvider>-->
 5           <dbProvider>Oracle.DataAccess.Client.OracleConnection,Oracle.DataAccess</dbProvider>
 6           <connectionString>Data Source=orcl;User ID=oracle_user; Password=password;</connectionString>
 7 
 8           <commandText>insert into RS_LOGTABLE (log_user,log_level,log_date,log_message) values(:log_user,:log_level,:log_date,:log_message)</commandText>
 9 
10           <parameter name=":log_user" layout="${machinename}"/>
11           <parameter name=":log_level" layout="${level}"/>
12           <parameter name=":log_date" layout="${date}"/>
13           <parameter name=":log_message" layout="${message}"/>
14 
15       </target>
16 </targets>
17 
18  <rules>
19       <logger name="oracleDbLog" minlevel="Debug" writeTo="oraclelog" />
20   </rules>
Oracle.DataAccess.Client Log配置

C#调用代码:

   Logger oracleLogger = LogManager.GetLogger("oracleDbLog");

            oracleLogger.Error(new Exception("自定义异常oracle"), "错误信息 oracledb", string.Empty);

 执行结果:

 

写入mysql,需应用MySql.Data程序集,安装Install-Package MySql.Data -Version 6.9.9,配置文件如下:

 1 <targets>
 2  <target name="MySQLLog" type="Database">
 3           <dbProvider>MySql.Data.MySqlClient.MySqlConnection,MySql.Data</dbProvider>
 4           <connectionString>Server=192.168.0.2;Uid=root;Pwd=root;Database=mydb;</connectionString>
 5 
 6           <commandText>insert into t_nlog (log_user,log_level,log_date,log_message) values(@log_user,@log_level,@log_date,@log_message)</commandText>
 7 
 8           <parameter name="@log_user" layout="${machinename}"/>
 9           <parameter name="@log_level" layout="${level}"/>
10           <parameter name="@log_date" layout="${date}"/>
11           <parameter name="@log_message" layout="${message}"/>
12       </target>
13 </targets>
14 
15 <rules>
16  <logger name="*" minlevel="Debug" writeTo="MySQLLog" />
17 </rules>      
NLog Mysql

执行结果:

 

文件日志异常模板:

      <target name="logfile" xsi:type="File" fileName="${basedir}/nlogs/${shortdate}.log"  layout="${longdate}|${level}||${logger} ${message}| ${exception:format=tostring}" />

 NLog日志写入到MongoDB,安装NLog.Mongo

PM> Install-Package NLog.Mongo
配置文件:
 1  <extensions>
 2         <add assembly="NLog.Mongo"/>
 3     </extensions>
 4 
 5    <target xsi:type="Mongo"
 6        name="mongoDefault"
 7        connectionString="mongodb://192.168.0.226:6111/NLogging"
 8        collectionName="DefaultLog"
 9        cappedCollectionSize="26214400">
10           <property name="ThreadID" layout="${threadid}" bsonType="Int32" />
11           <property name="ThreadName" layout="${threadname}" />
12           <property name="ProcessID" layout="${processid}" bsonType="Int32" />
13           <property name="ProcessName" layout="${processname:fullName=true}" />
14           <property name="UserName" layout="${windows-identity}" />
15       </target>
16 
17  <rules>
18     
19       <logger name="*" level="Debug" writeTo="mongoDefault" />
20   </rules>
NLog.config

 执行结果如下:

 参考:https://github.com/loresoft/NLog.Mongo

 


以上是关于log4net 发布到生产环境不写日志的解决方法的主要内容,如果未能解决你的问题,请参考以下文章

Asp.Net Core Log4Net 配置分多个文件记录日志(不同日志级别)

磨刀不误砍柴工:统一日志系统 Log4Net/ExceptionLess

Log4net

记录一次生产环境不打印sql日志的解决办法

日志记录工具 log4net 的配置与使用

log4net记录(转)