【问题标题】:Apache log4net changing logging level textApache log4net 更改日志记录级别文本
【发布时间】:2017-03-08 05:10:49
【问题描述】:

在 Apache Log4net 日志实用程序中,%level 模式输出记录器的日志级别,例如:如果我调用log.Warn(""),则输出为Warn。有什么办法可以改变输出文本。例如,log.Info("") 输出 Information 而不是 INFO。

【问题讨论】:

  • 检查模式(方法)是否可以被覆盖

标签: c# xml log4net log4net-configuration


【解决方案1】:

您可以做的一件事是create a custom log event, 并在必要时修改您的 PatternLayout 格式。

示例用法(来自链接):

您需要做的第一件事是使用 LogManager 创建和注册新级别,如下所示:

log4net.Core.Level authLevel = new log4net.Core.Level(50000, "Auth");
log4net.LogManager.GetRepository().LevelMap.Add(authLevel);
It’s important that you do this before configuring log4net.

添加一些扩展方法使得开始使用新的日志级别变得非常简单:

public static class SecurityExtensions
{
    static readonly log4net.Core.Level authLevel = new log4net.Core.Level(50000, "Auth");

    public static void Auth(this ILog log, string message)
    {
        log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, 
            authLevel, message, null);
    }

    public static void AuthFormat(this ILog log, string message, params object[] args)
    {
        string formattedMessage = string.Format(message, args);
        log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType,
            authLevel, formattedMessage, null);
    }

}

就是这样——现在我可以开始在任何 ILog 实例上使用我的新“Auth”日志记录级别,如下所示:

SecurityLogger.AuthFormat("User logged in with id {0} from IP address {1}", id, Request.UserHostAddress);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2014-09-01
    • 2023-04-11
    • 2016-02-20
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多