2023年11月9日 星期四

Log4net如何設定才能在windows service中正常寫入log的步驟

Log4net如何設定才能在windows service中正常寫入


1. 在 AssemblyInfo.cs 加入以下語法:


[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", Watch = true)]


2. Log4net.Config

<configuration>

<log4net>

  <appender name="ConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">

    <layout type="log4net.Layout.PatternLayout">

      <conversionPattern value="%date %level [%thread] %logger{1} %username - %message%newline" />

    </layout>

    <mapping>

      <level value="WARN" />

      <foreColor value="Yellow, HighIntensity" />

    </mapping>

    <mapping>

      <level value="ERROR" />

      <foreColor value="Red, HighIntensity" />

    </mapping>

  </appender>

  <appender name ="RollingLogFileAppender" type ="log4net.Appender.RollingFileAppender">

    <param name ="File" value ="logs/"/>

    <param name ="AppendToFile" value ="true"/>

    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

    <param name ="MaxSizeRollBackups" value ="10"/>

    <param name ="StaticLogFileName" value ="false"/>

    <param name ="DatePattern" value ="yyyyMM/yyyyMMdd&quot;.log&quot;"/>

    <param name ="RollingStyle" value ="Date"/>

    <layout type ="log4net.Layout.PatternLayout">

      <param name ="ConversionPattern" value ="%date %level [%thread] %logger{1} - %message%newline"/>

    </layout>

  </appender>

  <root>

    <level value="ALL" />

    <appender-ref ref="ConsoleAppender" />

    <appender-ref ref="RollingLogFileAppender" />

  </root>

</log4net>


</configuration>

3. C# 程式宣告

private static readonly log4net.ILog log = log4net.LogManager.GetLogger

   (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

4. 寫log


log.Info("test");