【一】、.net core 3.1 创建windows服务并集成Serilog的步骤记录

1、新建项目

  选择“Worker Service”,如下图:

 

2、添加nuget引用

  Microsoft.Extensions.Hosting.WindowsServices

  Serilog.Extensions.Hosting

  Serilog.Sinks.Console

  Serilog.Sinks.File

3、修改Program的Main方法

        public static void Main(string[] args)
        {
            var baseDir = AppDomain.CurrentDomain.BaseDirectory;
            var logfile = Path.Combine(baseDir, "log", "log.txt");
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console(LogEventLevel.Information, theme: AnsiConsoleTheme.Literate)
                .WriteTo.File(logfile, LogEventLevel.Information, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 90)
                .CreateLogger();
            try
            {
                Log.Information("服务启动成功!" + DateTime.Now.ToString());
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception e)
            {
                Log.Fatal(e, "启动出错了!");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

4、修改Program里的CreateHostBuilder

代码如下:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            })
            .UseSerilog();

5、测试Worker里的日志记录功能

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }

上面的代码是visual在创建项目时自带的,直接运行,就会在log文件夹里新建日志文件,然后记下日志如下:

  示例代码地址:https://download.csdn.net/download/jiancaixing/20629212

posted @ 2021-07-29 16:10  星星c#  阅读(404)  评论(0编辑  收藏  举报