美文网首页
asp.net core 日志组件 serilog

asp.net core 日志组件 serilog

作者: elef | 来源:发表于2019-01-18 15:27 被阅读64次

    参考

    安装 serilog

    $ dotnet add package Serilog.AspNetCore
    $ dotnet add package Serilog.Settings.Configuration
    
    $ dotnet add package Serilog.Sinks.Console
    $ dotnet add package Serilog.Sinks.RollingFile
    

    配置文件修改

    安装组件 Serilog.Settings.Configuration 后,serilog就可以使用 .net core 的配置文件了

    appsettings.json

    {
      "Serilog": {
        "WriteTo": [
          {
            "Name": "RollingFile",
            "Args": { "pathFormat": "log-{Date}.txt" }
          }
        ],
        "MinimumLevel": {
          "Default": "Debug",
          "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
          }
        }
      }
    }
    

    安装 Serilog.Sinks.RollingFile 后,可以将日志输出到以日期组织的文件中,可在配置文件中设置文件生成的规则及路径。

    将 serilog 作为中间件注入

    Program.cs

    ....
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using Serilog;
    using Serilog.Events;
    
    namespace Demo.API
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();
            }
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>().UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                .ReadFrom.Configuration(hostingContext.Configuration)
                .Enrich.FromLogContext()
                .WriteTo.Console());
                ## 注入 serilog
        }
    }
    

    在控制器中使用日志组件

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authorization;
    
    namespace Demo.API.Controllers
    {
        [Authorize]
        [Route("Api/[controller]")]
        [ApiController]
        public class UserController : ControllerBase
        {
            private readonly UserManager<UserIdentity> _userManager;
            private readonly ILogger _logger;
    
            public UserController(UserManager<UserIdentity> userManager, ILoggerFactory logFactory)
            {
                _userManager = userManager;
                _logger = logFactory.CreateLogger<UserController>();
            }
    
            /// <summary>
            /// 用户注册
            /// </summary>
            /// <param name="model">注册实体模型</param>
            /// <returns></returns>
            [Route("Register")]
            [AllowAnonymous]
            [HttpPost]
            public async Task<ApiResult> Register(RegisterModel model)
            {
                _logger.LogInformation("开始注册=", model.PhoneNumber);
    
                if (!ModelState.IsValid)
                {
                    return ApiResultUtil.Fail("数据不合法!");
                }
                try
                {   
                    IdentityResult result = null;
                    var user = await _userManager.FindByNameAsync(model.UserName);
    
                    if (user != null)
                        return ApiResultUtil.Fail("注册失败: 帐号重复");
    
                    user = new UserIdentity { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber };
                    result = await _userManager.CreateAsync(user, model.Password);
    
                    if (result.Succeeded)
                    {
                        return ApiResultUtil.Success();
                    }
                    else
                    {
                        return ApiResultUtil.Fail("注册失败!");
                    }
                }
                catch (Exception ex)
                {   
                    _logger.LogError(0, ex, "注册失败:" + ApiResultUtil.GetMessage(ex));
                    return ApiResultUtil.Fail("注册失败!");
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:asp.net core 日志组件 serilog

          本文链接:https://www.haomeiwen.com/subject/peundqtx.html