# 十四、日志管理

## 日志作用

简单来说，系统日志记录是记录系统（程序）的允许状态。为什么要记录日志呢？一般有下面几个方法的需求：

1. 记录用户操作的审计日志，甚至有的时候就是监管部门的要求。
2. 快速定位问题的根源
3. 追踪程序执行的过程。
4. 追踪数据的变化
5. 数据统计和性能分析
6. 采集运行环境数据

一般在程序上线之后，一旦发生异常，第一件事就是要弄清楚当时发生了什么。用户当时做了什么操作，环境有无影响，数据有什么变化，是不是反复发生等，然后再进一步的确定大致是哪个方面的问题。确定是程序的问题之后再交由开发人员去重现、研究、提出解决方案。

这时，日志就给我们提供了第一手的资料。

## 日志分类

* 系统（程序）运行日志
* 业务处理日志
* 代码调试日志
* 审计日志

目前除了审计日志功能还未实现，其余的在框架内部都可正常使用。

## 使用日志组件记录日志

### 如何配置

默认情况下，Hoa Framework 已经启用了 asp.net core 内置的日志程序，在 `Hoa.Web.Host.Program.cs` 配置如下：

```csharp
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Hoa.Web.Host
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                // 配置日志组件 BEGIN
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                })
                // 配置日志组件 END
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
```

`Hoa.Web.Host.appsetting.json` 配置如下：

```javascript
{
  "Logging": {
    "LogLevel": {  最低日志记录级别
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  // ....
}
```

### 使用日志记录

日志组件已经默认在构造函数中注入了，使用示例：

```csharp
public class AboutModel : PageModel
{
    private readonly ILogger _logger;

    public AboutModel(ILogger<AboutModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {
        _logger.LogInformation("Message displayed: {Message}", "你的日志");
    }
}
```

更多日志详情见[可查看官方文档](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monksoul.gitbook.io/hoa/rijiguanli.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
