简体   繁体   English

log4net从自定义appender访问上下文属性

[英]log4net accessing context properties from custom appender

I am using log4net with a custom appender that logs to Azure Storage Tables, and am having issues accessing log4net.GlobalContext properties from within my Appender. 我正在使用log4net和一个自定义appender,它会记录到Azure存储表,并且在我的Appender中访问log4net.GlobalContext属性时遇到问题。 I am logging from inside an Azure Function. 我从Azure函数内部进行日志记录。

The appending is pretty straight forward and simple and works fine, but I would like to add a couple custom properties - one of which is an InvocationId and only accessible from the Azure Functions, so i would like to know the best way to achieve this. 附加是非常简单和简单的工作正常,但我想添加一些自定义属性 - 其中一个是InvocationId,只能从Azure功能访问,所以我想知道实现这一目标的最佳方法。

Any idea what I'm missing? 知道我错过了什么吗?

Appender 追加程序

protected override void Append(LoggingEvent loggingEvent)
{
  _tableCtx.Log(new LogEntry
                {
                  Timestamp = loggingEvent.TimeStamp,
                  Message = loggingEvent.RenderedMessage,
                  Level = loggingEvent.Level.Name,
                  // properties is always empty
                  InvocationId = loggingEvent.Properties["InvocationId"],
                  PartitionKey = loggingEvent.LoggerName,
                 });
}

Azure Function Azure功能

public static async Task<HttpResponseMessage> MyFunction([HttpTrigger(AuthorizationLevel.Function, "post")]HttpRequestMessage req, ILogger log, ExecutionContext context)
{

  log4net.GlobalContext.Properties["InvocationId"] = context.InvocationId;
  using (var config = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyFunc.logging.config"))
  {
      log4net.Config.XmlConfigurator.Configure(config);
  }

   var log = LogManager.GetLogger(context.FunctionName);
}

Try 尝试

loggingEvent.GetProperties()["InvocationId"]

or 要么

loggingEvent.LookupProperty("InvocationId")

See here for more details 有关详细信息,请参见此处

You have to set the Property after you initialize log4net: 初始化log4net后,您必须设置该属性:

  using (var config = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyFunc.logging.config"))
  {
      log4net.Config.XmlConfigurator.Configure(config);
  }

  var log = LogManager.GetLogger(context.FunctionName);

  log4net.GlobalContext.Properties["InvocationId"] = context.InvocationId;

You also only have to initialize log4net when it is not yet initialized. 您还必须在尚未初始化时初始化log4net。 Doing it on every call is not very efficient. 每次通话都这样做效率不高。

我最终做到了这一点,这比我想象的要简单。

log4net.LogicalThreadContext.Properties["InvocationId"].ToString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM