c# – 如何在log4net消息中添加类别前缀?

c# – 如何在log4net消息中添加类别前缀?,第1张

概述我想为现有日志消息上的所有消息添加类别前缀.但是,将此前缀逐个添加到所有现有日志记录消息中非常繁琐.有没有办法可以在类级别添加一个属性,那么这个类中的所有消息都会记录到某个类别? 而不是现在的方式如下, Log.Info("[Ref] Level 1 Starts ..."); 我真的想要这样或类似的方式来定义log4net.ILog. [LoggingCategory("Ref")]publi 我想为现有日志消息上的所有消息添加类别前缀.但是,将此前缀逐个添加到所有现有日志记录消息中非常繁琐.有没有办法可以在类级别添加一个属性,那么这个类中的所有消息都会记录到某个类别?

而不是现在的方式如下,

Log.Info("[Ref] Level 1 Starts ...");

我真的想要这样或类似的方式来定义log4net.ILog.

[Loggingcategory("Ref")]public class MyClass {   public voID MyMethod()   {        Log.Info("Level 1 Starts ...");   }}
解决方法 有趣的问题,粗略的尝试……

Log4NetLogger – 日志适配器

public class Log4NetLogger{    private Readonly ILog _logger;    private Readonly string _category;    public Log4NetLogger(Type type)    {        _logger = LogManager.GetLogger(type);        _category = Getcategory();    }    private string Getcategory()    {        var attributes = new StackFrame(2).getmethod().DeclaringType.GetCustomAttributes(typeof(LoggingcategoryAttribute),false);        if (attributes.Length == 1)        {            var attr = (LoggingcategoryAttribute)attributes[0];            return attr.category;        }        return string.Empty;    }    public voID DeBUG(string message)    {        if(_logger.IsDeBUGEnabled) _logger.DeBUG(string.Format("[{0}] {1}",_category,message));    }}

LoggingcategoryAttribute – 适用于类

[AttributeUsage(AttributeTargets.Class)]public class LoggingcategoryAttribute : Attribute{    private Readonly string _category;    public LoggingcategoryAttribute(string category)    {        _category = category;    }    public string category { get { return _category; } }}

LogTester – 一个测试实现

[Loggingcategory("LT")]public class LogTester{    private static Readonly Log4NetLogger Logger = new Log4NetLogger(typeof(LogTester));    public voID test()    {        Logger.DeBUG("This log message should have a prepended category");    }}
总结

以上是内存溢出为你收集整理的c# – 如何在log4net消息中添加类别前缀?全部内容,希望文章能够帮你解决c# – 如何在log4net消息中添加类别前缀?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1251525.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存