让Log4Net 立即写日志文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/rocklee/article/details/78421617

         Log4Net会将日志缓冲到内存, app退出时才会写入磁盘, 但调试阶段常常希望在app运行时即时看到产生的日志, 这时候需要在配置里面增加ImmediateFlush参数 :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <section name="SerialBarcode.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />        
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
    <userSettings>
        <SerialBarcode.Properties.Settings>
            <setting name="user" serializeAs="String">
                <value>postgres</value>
            </setting>
            <setting name="port" serializeAs="String">
                <value>5432</value>
            </setting>
            <setting name="host" serializeAs="String">
                <value>xxxx</value>
            </setting>
            <setting name="pass" serializeAs="String">
                <value>password</value>
            </setting>
            <setting name="database" serializeAs="String">
                <value>xxxxdb</value>
            </setting>
        </SerialBarcode.Properties.Settings>        
    </userSettings>
  <log4net>
    <!--定义输出到文件中-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--定义文件存放位置-->
      <file value="log\\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyyMM\\yyyyMMdd'.txt'"/>
      <staticLogFileName value="false"/>
	  
      <param name="ImmediateFlush" value="true" />
	 
      <param name="MaxSizeRollBackups" value="100"/>
      <layout type="log4net.Layout.PatternLayout">
        <!--每条日志末尾的文字说明-->
        <!--输出格式-->
        <!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
        <conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%newline %n"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <!--文件形式记录日志-->
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
</configuration>


发布时需要带上app名.exe.config这个配置文件, 否则log4net则不工作. 若关闭立即写磁盘的功能,则需要将<param name="ImmediateFlush" value="true" />这个注释掉即可 .


展开阅读全文

没有更多推荐了,返回首页