[英]Structured Logging in Azure Functions
我试图让结构化日志记录在 Azure Function 中工作,但它在我这边不起作用。
我写了一个这样的简单应用程序
[FunctionName("Dummy")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest request, ILogger log)
{
var instance = new User
{
Name1 = "foo",
Name2 = "bar"
};
log.LogInformation("Test1: {$Test}", instance);
log.LogInformation("Test2: {@Name}", instance);
log.LogInformation("Test3: {@Name}", new { Name1 = "abc", Name2 = "def" });
log.LogInformation("Test4: {Vorname} {Nachname}", instance.Name1, instance.Name2);
return new OkResult();
}
public class User
{
public string Name1 { get; set; }
public string Name2 { get; set; }
}
output 看起来像这样:
Test1: Company.FunctionApp1.Function+User
Test2: Company.FunctionApp1.Function+User
Test3: { Name1 = abc, Name2 = def }
Test4: foo bar
我不知道为什么解构对动态类型起作用,但对定义的 class 不起作用。 我发现了许多正常日志记录的示例,没有 object 的解构,但我认为它应该开箱即用。
我错过了什么吗?
测试 3 打印为{ Name1 = abc, Name2 = def }
,因为定义的类型为匿名 object,编译器为其生成ToString()
方法以返回具有属性和值映射的字符串。
检查此讨论。
您可以通过反编译来验证。
因为,Test2 和 Test1 使用 object 并且没有覆盖ToString()
定义,这就是返回 TypeName 的原因。
正确的方法是 go 与 Test4 以便Vorname
和Nachname
记录为自定义属性并可用于过滤。
user1672994 的回答是对的,您可以执行以下操作:
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace FunctionApp96
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var instance = new User
{
Name1 = "foo",
Name2 = "bar"
};
log.LogInformation("Test1: {$Test}", instance);
log.LogInformation("Test2: {@Name}", instance);
log.LogInformation("Test3: {@Name}", new { Name1 = "abc", Name2 = "def" });
log.LogInformation("Test4: {Vorname} {Nachname}", instance.Name1, instance.Name2);
return new OkObjectResult("");
}
}
public class User
{
public override string ToString()
{
string str = "{ Name1 = " + Name1 + ", Name2 =" + Name2 + " }";
return str;
}
public string Name1 { get; set; }
public string Name2 { get; set; }
}
}
你会得到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.