From 6f263df59a895b6bcc2fe22b9626ddd81537c217 Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Sun, 27 Nov 2022 13:37:06 -0600 Subject: AƱadido job de loggeo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jobs/LoggerJob.cs | 36 ++++++++++++++++++++++++++++++++++++ Program.cs | 4 ++++ wwwroot/Log.txt | 12 ++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 Jobs/LoggerJob.cs create mode 100644 wwwroot/Log.txt diff --git a/Jobs/LoggerJob.cs b/Jobs/LoggerJob.cs new file mode 100644 index 0000000..72a571f --- /dev/null +++ b/Jobs/LoggerJob.cs @@ -0,0 +1,36 @@ +// Singleton service. +namespace BackendPIA.Jobs { + public class LoggerJob : IHostedService { + private Timer? _timer; + private readonly IWebHostEnvironment _env; + private readonly string _log_file = "Log.txt"; + + public LoggerJob(IWebHostEnvironment env) { + _env = env; + } + + public Task StartAsync(CancellationToken cancel_token) { + _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(5)); + + return Task.CompletedTask; + } + + public void DoWork(object state) { + LogToFile("Executing task\n" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")); + } + + public Task StopAsync(CancellationToken cancel_token) { + LogToFile("Stopping task...\n"); + _timer.Dispose(); + return Task.CompletedTask; + } + + private void LogToFile(string message) { + var path = $@"{_env.ContentRootPath}/wwwroot/{_log_file}"; + + using (StreamWriter w = new StreamWriter(path, append: true)) { + w.WriteLine(message); + } + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 793aa1e..3df7c40 100644 --- a/Program.cs +++ b/Program.cs @@ -9,6 +9,7 @@ using System.Text; using Microsoft.EntityFrameworkCore; using BackendPIA; using BackendPIA.Models; +using BackendPIA.Jobs; using BackendPIA.Policies; using BackendPIA.Services; @@ -26,6 +27,9 @@ builder.Services.AddIdentity().AddEntityFrameworkStor // Automapper configuration. builder.Services.AddAutoMapper(typeof(Program)); +// Hosted services. +builder.Services.AddHostedService(); + // Custom services configuration. builder.Services.AddSingleton(s => new TokenGenerator(builder.Configuration["Jwt:Key"])); builder.Services.AddScoped(); diff --git a/wwwroot/Log.txt b/wwwroot/Log.txt new file mode 100644 index 0000000..edf5f19 --- /dev/null +++ b/wwwroot/Log.txt @@ -0,0 +1,12 @@ +Executing task +27/11/2022 01:22:08 +Stopping task... + +Executing task +27/11/2022 01:25:41 +Executing task +27/11/2022 01:30:41 +Executing task +27/11/2022 01:35:41 +Stopping task... + -- cgit v1.2.3