Serilog可以返回结果操作的值而不是数据类型吗?

时间:2018-09-24 20:16:34

标签: asp.net-core serilog

我使用Serilog.AspNetCore软件包在.net core 2.1 Web API中拥有Seri​​log。调用某个动作时,将记录传入的参数:

[INF] Executing action method WebApi.Controllers.ValuesController.Get (WebApi) with arguments (["4"]) - Validation state: "Valid"

但是当操作完成时,我得到以下不太有用的行:

[INF] Executed action method WebApi.Controllers.ValuesController.Get (WebApi), returned result Microsoft.AspNetCore.Mvc.ObjectResult in 8.2537ms.
[INF] Executing ObjectResult, writing value of type 'System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]'.

我希望使用实际值。例如,字典应该只是json。

是否有方法可以覆盖此默认行为?

1 个答案:

答案 0 :(得分:2)

对于 Serilog ,它可以返回json数据类型,但是您不能更改Executing ObjectResult的内置返回值。这是由ObjectResultExecuting控制的,并且是硬代码。

public static void ObjectResultExecuting(this ILogger logger, object value)
{
    if (logger.IsEnabled(LogLevel.Information))
    {
        var type = value == null ? "null" : value.GetType().FullName;
        _objectResultExecuting(logger, type, null);
    }
}

ObjectResultExecuting记录类型而不是值。我认为这是为了获得更好的性能。您可以假设,如果将响应序列化为字符串,则会浪费很多性能,因此不需要这样做。

如果您希望记录特定的响应,则可以尝试自己登录该方法。

[Produces("application/json")]
[Route("api/[controller]")]
public class SerilogController : Controller
{
    private readonly ILogger<SerilogController> _log;
    public SerilogController(ILogger<SerilogController> log)
    {
        _log = log;
    }

    [HttpGet]
    public IEnumerable<string> Get(string password)
    {
        _log.LogInformation(JsonConvert.SerializeObject(new string[] { "value1", "value2" }));
        return new string[] { "value1", "value2" };
    }
}