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}"
}
}
],
}
}
참조
'프로그래밍' 카테고리의 다른 글
Git 개발자가 Git을 구성하는 방법 (0) | 2025.03.10 |
---|---|
[LLM] Ollama 모델 사용기 - 2 (0) | 2025.01.09 |
[LLM] Ollama 모델 사용기 - 1 (0) | 2025.01.09 |
[WPF] MaterialDesign 아이콘 사용하기 (0) | 2024.12.17 |
클래스 간의 관계 (UML) (0) | 2024.12.06 |