WPF項目使用日誌

提問

WPF項目如何使用日誌

回答

  1. 引入nuget log4net

  2. 加入配置特性

[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

  1. 添加配置文件
    app.config
<configuration>
    <configSections>
        <!--log4net配置-->
        <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
    </configSections>
    <!--log4net配置-->
    <log4net>
        <!--定義輸出到文件中-->
        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
            <!--定義文件存放位置-->
            <!--file可以指定具體的路徑 D://logfile.txt。-->
            <file value="C://ProgramData//NbApi//configlogfile.txt"/>
            <!--如果放在Debug下,當然名字你可以改 -->
            <!--<file value="log//logfile.txt"/>-->
            <appendToFile value="true"/>
            <rollingStyle value="Date"/>
            <!--備份log文件的個數最多10個-->
            <maxSizeRollBackups value="10" />
            <!--每個log文件最大是2M,如果超過2M將重新創建一個新的log文件,並將原來的log文件備份。-->
            <maximumFileSize value="2MB" />
            <datePattern value="yyyyMMdd-HH:mm:ss"/>
            <layout type="log4net.Layout.PatternLayout">
                <!--輸出格式-->
                <!--樣例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
                <conversionPattern value="[%date] [%-5level] %message%newline"/>
            </layout>
        </appender>
        <!--定義日誌的輸出媒介-->
        <root>
            <!--指定將此級別及以上的log打印到log文件中-->
            <level value="DEBUG"/>
            <!--文件形式記錄日誌-->
            <appender-ref ref="LogFileAppender"/>
        </root>
    </log4net>
</configuration>
  1. 幫助類
using log4net;

namespace NBApi.Configurator;

public class LogObject
{
    public static ILog Log(string LoggerName)
    {   
        return LogManager.GetLogger(LoggerName); } 
}
  1. 使用
public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType);
。。。
Log.Info( $"執行時間:{DateTime.Now:yyyy-MM-dd HH:mm:ss}:清除SyncedTags.log");

參考

https://www.cnblogs.com/likui-bookHouse/p/11052053.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章