본문 바로가기
C#

[C#] Worker 프로젝트에서 appsettings.json 불러오기, Serilog 사용하여 로컬 파일 로그 저장.

by Jcoder 2023. 10. 24.

appsettins.json 파일

{
    "Logging": {
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "Test": {
    "ApiUrl": "https://test.com",
    "Time": "0400"
    },
    "Prod": {
    "ApiUrl": "https://prod.com",
    "Time": "0400"
    },
    "slackUrl": "https://hooks.slack.com/services/123123324"
}

Program.cs

using Serilog;  
using Serilog.Events; 

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((context, builder) =>
    {
        builder.SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    })
    .ConfigureServices(services => { services.AddHostedService<Worker>(); })
    .UseSerilog((context, configuration) =>
    {
        configuration.MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .WriteTo.File("./logs/logs-worker-.txt", rollingInterval: RollingInterval.Day,
                 outputTemplate:"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] {Message:lj}{NewLine}{Exception}",
                 shared:true);
            //.WriteTo.File(new CompactJsonFormatter(), path:"./logs/logs-.json", rollingInterval: RollingInterval.Day);
    })
    .Build();

host.Run();

 

Worker.cs

using System.Text;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IConfiguration _configuration;
    private readonly ILogger<api> _apiLogger;
    private readonly Dictionary<string, api> _apis = new();
    
    private string? _slackUrl;

    public Worker(ILogger<Worker> logger, IConfiguration configuration, ILogger<api> apiLogger)
    {
        _logger = logger;
        _configuration = configuration;
        _apiLogger = apiLogger;
    }

    public override Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("장기파일 이동 자동 프로그램 시작합니다.");
        _logger.LogInformation("환경변수를 읽기 시작");
        GetEnvironmentVariables();
        _logger.LogInformation("환경변수를 읽기 완료");
        return base.StartAsync(cancellationToken);
    }
    
    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            foreach (string key in _Apis.Keys)  
            {
                if (DateTime.Now.ToString("HHmm").Equals(_storageApis[key].Time))
                {
                    StringBuilder sb = new();
                    sb.AppendLine($"[Program {key} Start]");

                    _logger.LogInformation(sb.ToString());
                }
            }
            await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
        }
    }
    
    public override Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Worker Stop");
        return base.StopAsync(cancellationToken);
    }

    private void GetEnvironmentVariables()
    {
        _slackUrl = _configuration.GetValue<string>("slackUrl") ?? "https://hooks.slack.com/services/12341234";
        
        var apiUrl = _configuration.GetValue<string>("Prod:ApiUrl") ?? "https://prod.com";
        var apiTime = _configuration.GetValue<string>("Prod:ApiTime") ?? "0500";
        _apis.Add("Prod", new(_apiLogger, apiUrl, apiTime));
        
        apiUrl = _configuration.GetValue<string>("Test:ApiUrl") ?? "https://test.com";
        apiTime = _configuration.GetValue<string>("Test:ApiTime") ?? "0400";
        _apis.Add("Test", new(_apiLogger, apiUrl, apiTime));
    }
}