WPF项目使用日志
提问
WPF项目如何使用日志
回答
-
引入nuget log4net
-
加入配置特性
[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)]
- 添加配置文件
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>
- 帮助类
using log4net;
namespace NBApi.Configurator;
public class LogObject
{
public static ILog Log(string LoggerName)
{
return LogManager.GetLogger(LoggerName); }
}
- 使用
public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType);
。。。
Log.Info( $"执行时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}:清除SyncedTags.log");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2023-04-19 属性字段为什么要在构造函数中初始化
2016-04-19 treeview 与tabControl组合使用