从字符串创建强类型 log4net 级别

发布于 2024-11-03 22:42:56 字数 2706 浏览 1 评论 0 原文

我注意到 log4net 有一个强类型的 级别类。有谁知道是否有办法通过解析日志级别字符串来创建 Level 对象?

例如:

我想将错误级别字符串“ERROR”解析为等效的 log4net.Core.Level.Error 对象,对于其他日志记录级别也是如此。

我编写了自己的(天真的)方法来执行此操作(见下文),但我希望 log4net 内部有一些东西可以为我执行此操作。

谢谢!

    public static Level ParseLevel(string level)
    {
        switch (level.ToUpperInvariant())
        {
            case "ALERT":
                return log4net.Core.Level.Alert;
            case "ALL":
                return log4net.Core.Level.All;
            case "CRITICAL":
                return log4net.Core.Level.Critical;
            case "DEBUG":
                return log4net.Core.Level.Debug;
            case "EMERGENCY":
                return log4net.Core.Level.Emergency;
            case "ERROR":
                return log4net.Core.Level.Error;
            case "FATAL":
                return log4net.Core.Level.Fatal;
            case "FINE":
                return log4net.Core.Level.Fine;
            case "FINER":
                return log4net.Core.Level.Finer;
            case "FINEST":
                return log4net.Core.Level.Finest;
            case "INFO":
                return log4net.Core.Level.Info;
            case "NOTICE":
                return log4net.Core.Level.Notice;
            case "OFF":
                return log4net.Core.Level.Off;
            case "SEVERE":
                return log4net.Core.Level.Severe;
            case "TRACE":
                return log4net.Core.Level.Trace;
            case "VERBOSE":
                return log4net.Core.Level.Verbose;
            case "WARN":
                return log4net.Core.Level.Warn;
            default:
                throw new Exception("Invalid logging level specified");
        }
    }

编辑:根据 Wily 博士的学徒的建议,以下是我最终使用 LevelMap

    using System;
    using System.Linq;

    public static Level ParseLevel(string level)
    {
        var loggerRepository = LoggerManager.GetAllRepositories().FirstOrDefault();

        if (loggerRepository == null)
        {
            throw new Exception("No logging repositories defined");
        }

        var stronglyTypedLevel = loggerRepository.LevelMap[level];

        if (stronglyTypedLevel == null)
        {
            throw new Exception("Invalid logging level specified");
        }

        return stronglyTypedLevel;
    }

I noticed log4net has a strongly typed Level class. Does anyone know if there's a way to create a Level object by parsing a log level string?

For example:

I want to parse the error level string "ERROR" into the equivalent log4net.Core.Level.Error object, and likewise for other logging levels.

I wrote my own (naive) method to do this (see below), but I was hoping there was something internal to log4net that would do this for me.

Thanks!

    public static Level ParseLevel(string level)
    {
        switch (level.ToUpperInvariant())
        {
            case "ALERT":
                return log4net.Core.Level.Alert;
            case "ALL":
                return log4net.Core.Level.All;
            case "CRITICAL":
                return log4net.Core.Level.Critical;
            case "DEBUG":
                return log4net.Core.Level.Debug;
            case "EMERGENCY":
                return log4net.Core.Level.Emergency;
            case "ERROR":
                return log4net.Core.Level.Error;
            case "FATAL":
                return log4net.Core.Level.Fatal;
            case "FINE":
                return log4net.Core.Level.Fine;
            case "FINER":
                return log4net.Core.Level.Finer;
            case "FINEST":
                return log4net.Core.Level.Finest;
            case "INFO":
                return log4net.Core.Level.Info;
            case "NOTICE":
                return log4net.Core.Level.Notice;
            case "OFF":
                return log4net.Core.Level.Off;
            case "SEVERE":
                return log4net.Core.Level.Severe;
            case "TRACE":
                return log4net.Core.Level.Trace;
            case "VERBOSE":
                return log4net.Core.Level.Verbose;
            case "WARN":
                return log4net.Core.Level.Warn;
            default:
                throw new Exception("Invalid logging level specified");
        }
    }

Edit: Based on Dr. Wily's Apprentice's recommendation, here's what I came up with in the end using the LevelMap:

    using System;
    using System.Linq;

    public static Level ParseLevel(string level)
    {
        var loggerRepository = LoggerManager.GetAllRepositories().FirstOrDefault();

        if (loggerRepository == null)
        {
            throw new Exception("No logging repositories defined");
        }

        var stronglyTypedLevel = loggerRepository.LevelMap[level];

        if (stronglyTypedLevel == null)
        {
            throw new Exception("Invalid logging level specified");
        }

        return stronglyTypedLevel;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

棒棒糖 2024-11-10 22:42:56

您可以使用反射来获取日志级别列表,并使用该列表来填充 LevelMap。

using System.Reflection;
using log4net.Core;

namespace MyUtils
{
    /// <summary>
    /// for getting the log level that belongs to a string
    /// </summary>
    public static class LogLevelMap
    {
        static LevelMap levelMap = new LevelMap();

        static LogLevelMap()
        {
            foreach (FieldInfo fieldInfo in typeof(Level).GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                if (fieldInfo.FieldType == typeof(Level))
                {
                    levelMap.Add((Level)fieldInfo.GetValue(null));
                }
            }
        }

        public static Level GetLogLevel(string logLevel)
        {
            if (string.IsNullOrWhiteSpace(logLevel))
            {
                return null;
            }
            else 
            {
                return levelMap[logLevel]; 
            }
        }
    }
}

You can use reflection to get the list of log levels and use this list to fill the LevelMap.

using System.Reflection;
using log4net.Core;

namespace MyUtils
{
    /// <summary>
    /// for getting the log level that belongs to a string
    /// </summary>
    public static class LogLevelMap
    {
        static LevelMap levelMap = new LevelMap();

        static LogLevelMap()
        {
            foreach (FieldInfo fieldInfo in typeof(Level).GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                if (fieldInfo.FieldType == typeof(Level))
                {
                    levelMap.Add((Level)fieldInfo.GetValue(null));
                }
            }
        }

        public static Level GetLogLevel(string logLevel)
        {
            if (string.IsNullOrWhiteSpace(logLevel))
            {
                return null;
            }
            else 
            {
                return levelMap[logLevel]; 
            }
        }
    }
}
踏月而来 2024-11-10 22:42:56

好吧,只要每个级别在 Level 类中定义为:

 public static readonly Level Warn;

我没有看到一个很好的方法来处理它(您可以使用反射来枚举属性,但我认为它不值得)。我看到的对代码的唯一改进是使用 Level.Name 中的值,而不是硬编码字符串值。

Well, as long as each level is defined in Level class as:

 public static readonly Level Warn;

I don't see a nice way to handle it (you could use reflection to enumerate properties, but i don't think it's worth). The only improvement to your code i see, instead of hard coded string values, use values from Level.Name instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文