我正在尝试在 Azure 函数中使用结构化日志记录,但它在我这边不起作用。
我写了一个这样的简单应用
[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; }
}
输出如下所示:
Test1: Company.FunctionApp1.Function+User
Test2: Company.FunctionApp1.Function+User
Test3: { Name1 = abc, Name2 = def }
Test4: foo bar
我不知道为什么解构对动态类型起作用,但对定义的类不起作用。我找到了许多没有对象解构的正常日志记录示例,但我认为它应该是开箱即用的。
我错过了什么吗?
答案 0 :(得分:0)
测试 3 打印为 { Name1 = abc, Name2 = def }
,因为定义的类型是匿名对象,编译器为其生成 ToString()
方法以返回具有属性和值映射的字符串。
查看 this 讨论。
您可以通过反编译来验证相同的内容。
因为 Test2 和 Test1 使用对象并且没有覆盖 ToString()
定义,这就是返回 TypeName 的原因。
正确的方法是使用 Test4,以便将 Vorname
和 Nachname
记录为自定义属性并可用于过滤。
答案 1 :(得分:0)
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; }
}
}
你会得到: