NLog 自定义日志级别值

发布于 2024-11-25 01:35:58 字数 104 浏览 0 评论 0原文

我有一个数据库,我正在尝试将消息写入其中,并希望使用 ${level} 布局,但我需要将其转换为 int 值以引用我自己的存储日志记录级别的表。是否可以将级别转换为配置中的枚举?还有其他想法吗?

I have a database I'm trying to write my messages to and would like to use the ${level} layout, but I need to translate it to the int value for reference to my own table that stores logging levels. Is it possible to maybe cast the level to my enum in config? Any other ideas?

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

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

发布评论

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

评论(3

南…巷孤猫 2024-12-02 01:35:58

我还没有检查过这一点,但我怀疑你应该能够为 NLog 编写自己的布局渲染器(插件)来完成你想做的事情。 NLog 是非常可插入的:)

布局渲染器外观的快速示例(未测试...):

[LayoutRenderer("intLevel", UsingLogEventInfo = true)]
public class IntLevel : LayoutRenderer
{
    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
        return 1;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        switch(logEvent.Level.LowercaseName)
        {
            case "trace":
                builder.Append(0);
                break;
            case "debug":
                builder.Append(1);
                break;
            case "info":
                builder.Append(2);
                break;
            case "warn":
                builder.Append(3);
                break;
            case "error":
                builder.Append(4);
                break;
            case "fatal":
                builder.Append(5);
                break;
            default:
                builder.Append(-1);
                break;
        }
    }
}

I have not checked this, but I suspect you should be able to just write your own layout renderer (plugin) for NLog to do what you want to do. NLog is very pluggable :)

A quick example of how a layout renderer could look (not tested...):

[LayoutRenderer("intLevel", UsingLogEventInfo = true)]
public class IntLevel : LayoutRenderer
{
    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
        return 1;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        switch(logEvent.Level.LowercaseName)
        {
            case "trace":
                builder.Append(0);
                break;
            case "debug":
                builder.Append(1);
                break;
            case "info":
                builder.Append(2);
                break;
            case "warn":
                builder.Append(3);
                break;
            case "error":
                builder.Append(4);
                break;
            case "fatal":
                builder.Append(5);
                break;
            default:
                builder.Append(-1);
                break;
        }
    }
}
半透明的墙 2024-12-02 01:35:58

尝试这个解决方案:

[LayoutRenderer("levelInt")]
public class NlogLevelToIntLayoutRenderer : LayoutRenderer
{
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(logEvent.Level.Ordinal);
    }
}

Try this solution:

[LayoutRenderer("levelInt")]
public class NlogLevelToIntLayoutRenderer : LayoutRenderer
{
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(logEvent.Level.Ordinal);
    }
}
夜访吸血鬼 2024-12-02 01:35:58

这是一个经过测试的布局渲染器,它将日志级别记录为整数。我获取日志级别的方式可能有点过分,但我正在经历 linq 阶段;-)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NLog;
using NLog.LayoutRenderers;

namespace MyNLogExtensions.NLog
{
  [LayoutRenderer("LogLevelOrdinal")]
  class LogLevelOrdinalLayoutRenderer : LayoutRenderer
  {
    IDictionary<LogLevel, int> ordinals;

    public override void  Initialize()
    {
      base.Initialize();

      ordinals = GetLogLevels()
                  .OrderBy(level => level)
                  .Select((level, index) => new { Level = level, Ordinal = index })
                  .ToDictionary( x => x.Level, x => x.Ordinal);
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
      int level = 0;

      if (!ordinals.TryGetValue(logEvent.Level, out level)) level = 99;

      builder.Append(level);
    }

    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
      return 1;
    }

    //
    // LogLevel is a static class with a static member for each of the different log levels.
    // The LogLevel ordinal is not exposed publically (i.e. an ordinal indicating the relative
    // "importance" of a LogLevel value).
    // The implementation of LogLevel.GetHashCode actually does return the ordinal, but it doesn't
    // seem right to rely on that implementation detail.
    // In the end, this LayoutRenderer is really just to allow for producing a numeric value to represent
    // a particular log level value's "position" relative to the other lob levels.  As such, 
    // We can just get all of the known log level values, order them (they are sortable), and assign our
    // own ordinal based on the position of the log level value in the resulting sorted list.
    //
    // This helper function exposes the known log level values as IEnumerable<LogLevel> so that we can
    // easily use LINQ to build a dictionary to map LogLevel to ordinal.
    //
    internal IEnumerable<LogLevel> GetLogLevels()
    {
      yield return LogLevel.Trace;
      yield return LogLevel.Debug;
      yield return LogLevel.Info;
      yield return LogLevel.Warn;
      yield return LogLevel.Error;
      yield return LogLevel.Fatal;
    }

  }
}

Here is a tested layout renderer that logs the log level as an integer. The way that I get the log levels is probably a little overboard, but I was going through a linq phase ;-)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NLog;
using NLog.LayoutRenderers;

namespace MyNLogExtensions.NLog
{
  [LayoutRenderer("LogLevelOrdinal")]
  class LogLevelOrdinalLayoutRenderer : LayoutRenderer
  {
    IDictionary<LogLevel, int> ordinals;

    public override void  Initialize()
    {
      base.Initialize();

      ordinals = GetLogLevels()
                  .OrderBy(level => level)
                  .Select((level, index) => new { Level = level, Ordinal = index })
                  .ToDictionary( x => x.Level, x => x.Ordinal);
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
      int level = 0;

      if (!ordinals.TryGetValue(logEvent.Level, out level)) level = 99;

      builder.Append(level);
    }

    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
      return 1;
    }

    //
    // LogLevel is a static class with a static member for each of the different log levels.
    // The LogLevel ordinal is not exposed publically (i.e. an ordinal indicating the relative
    // "importance" of a LogLevel value).
    // The implementation of LogLevel.GetHashCode actually does return the ordinal, but it doesn't
    // seem right to rely on that implementation detail.
    // In the end, this LayoutRenderer is really just to allow for producing a numeric value to represent
    // a particular log level value's "position" relative to the other lob levels.  As such, 
    // We can just get all of the known log level values, order them (they are sortable), and assign our
    // own ordinal based on the position of the log level value in the resulting sorted list.
    //
    // This helper function exposes the known log level values as IEnumerable<LogLevel> so that we can
    // easily use LINQ to build a dictionary to map LogLevel to ordinal.
    //
    internal IEnumerable<LogLevel> GetLogLevels()
    {
      yield return LogLevel.Trace;
      yield return LogLevel.Debug;
      yield return LogLevel.Info;
      yield return LogLevel.Warn;
      yield return LogLevel.Error;
      yield return LogLevel.Fatal;
    }

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