프로그래밍

Topshelf + Serilog

Victory_HA 2025. 3. 5. 11:39
using Microsoft.Extensions.Configuration;
using Serilog;
using System.Timers;
using Topshelf;
using Topshelf.Logging;
using Timer = System.Timers.Timer;

namespace TopshelfSample;

public class SampleService
{
    private readonly Timer _timer;
    static readonly LogWriter _log = HostLogger.Get<SampleService>();

    public SampleService()
    {
        _timer = new Timer(1000); // 1초마다 실행
        _timer.Elapsed += Timer_Elapsed;
    }

    public bool Start()
    {
        _timer.Start();
        _log.Info("service start!!");
        return true;
    }

    public bool Stop()
    {
        _timer.Stop();
        _log.Info("service stop!!");
        return true;
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _log.Info($"서비스 실행중 : {DateTime.Now}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

        ILogger logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        var testCode = HostFactory.Run(x =>
        {
            x.UseSerilog(logger);
            x.SetServiceName("Smaple topshelf service");
            x.SetDisplayName("Smaple topshelf service_Display");
            x.SetDescription("this is description.");
            x.Service<SampleService>(s =>
            {
                s.ConstructUsing(name => new SampleService());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });
        });
    }
}

appsettings.json

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs\\SampleService_.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7,  
          "outputTemplate": "{Timestamp:HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
        }
      }
    ],
  }
}

참조