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

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