简体   繁体   English

在Azure函数v2中添加中间件等

[英]Adding middleware or alike in Azure functions v2

I need to add correlationId to my logging context and I did it on my MVC project by adding CorrelationId nuget to the project and setting up its middleware, but I could not do the same in Azure functions. 我需要向我的日志记录上下文中添加correlationId,并在我的MVC项目中通过向项目中添加CorrelationId nuget并设置其中间件来做到这一点,但是在Azure函数中却无法做到这一点。

I have loaded the ICorrelationContextAccessor using Dependency injection and then set my correlationId like this: 我已经使用依赖注入加载了ICorrelationContextAccessor,然后像这样设置我的correlationId:

    [FunctionName("func1")]
    public async Task Run([ServiceBusTrigger("mytopic", "MySubscription", Connection = "ServiceBusConnectionString")]Message message)
    {
        _correlationContextAccessor.CorrelationContext = _correlationContextFactory.Create(message.CorrelationId, "X-Correlation-ID");
        _logger.LogInformation($"C# ServiceBus topic trigger function processed message: {message.MessageId}, {Encoding.UTF8.GetString(message.Body)}");

It works fine and I see my correlationId in the log line below and in my services in the function. 它工作正常,我在下面的日志行以及该函数的服务中看到我的correlationId。 The only part that I am missing is that I have logs regarding the start and finish of the function that still has no correlationId, which kind of make sense becaue when the function wants to log that it has received the message the correlationId is not set. 我唯一缺少的是我有关于该函数的开始和结束的日志,而该日志仍然没有correlationId,这是有道理的,因为当该函数想要记录它已收到未设置correlationId的消息时,就会记录该日志。

The short version is that you can't effect the logging code that runs before your function using the built in bindings. 简短的版本是,您无法使用内置绑定影响在函数运行之前运行的日志记录代码。

You won't be able to change that first "C# Timer trigger function processed message" as the message hasn't been read at that point-- it would be the same as trying to get the correlation ID set in your MVC project before reading the incoming HTTP request. 您将无法更改该第一条“ C#计时器触发函数已处理的消息”,因为此时尚未读取该消息,这与尝试在读取MVC项目中获取相关ID相同传入的HTTP请求。

You could add logging as soon as the message is first received by creating a custom binding . 您可以通过创建自定义绑定 ,在首次收到消息后立即添加日志记录。 I would encourage you to consider carefully whether or not it is worth building and maintaining a custom binding to get your logging setup a few lines sooner. 我鼓励您仔细考虑是否值得构建和维护自定义绑定,以便更快地进行日志记录设置。

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

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