제3자 로깅 서비스: Serilog, NLog, ELK Stack (Elasticsearch, Logstash, Kibana)와 같은 외부 로깅 라이브러리를 사용하여 로그를 특정 스토리지나 서비스로 보낼 수 있습니다.
1. NLog 패키지 설치
![](https://www.auctionpro.co.kr/wp-content/uploads/2024/07/image-6.png)
1 2 3 4 5 |
dotnet add package NLog.Web.AspNetCore dotnet add package NLog.Extensions.Logging dotnet add package NLog.Database |
1.1 MySQL 에 저장시 : 로그 디비컨넥션 오류 발생시 문제 많음 (비추)
![](https://www.auctionpro.co.kr/wp-content/uploads/2024/07/image-7.png)
1 2 3 |
dotnet add package MySql.Data |
2. Create the MySQL Database and Table
1 2 3 4 5 6 7 8 9 10 |
CREATE TABLE LogTable ( Id INT AUTO_INCREMENT PRIMARY KEY, Date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, Level VARCHAR(50) NOT NULL, Logger VARCHAR(255) NOT NULL, Message TEXT NOT NULL, Exception TEXT ); |
3. nlog.config 루트에 추가
NLog.Config 있을시 삭제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" internalLogLevel="Debug" internalLogFile="internal-nlog.txt"> <!-- Include the NLog.Web.AspNetCore package --> <extensions> <add assembly="NLog.Web.AspNetCore" /> </extensions> <!-- Define the targets --> <targets> <!-- Log to a file --> <target xsi:type="File" name="logfile" fileName="logs/logfile.txt" layout="${longdate} ${uppercase:${level}} ${logger} ${message} ${exception}" /> <!-- Log to the console --> <target xsi:type="Console" name="logconsole" layout="${longdate} ${uppercase:${level}} ${logger} ${message} ${exception}" /> <!-- Log to a MySQL database --> <target xsi:type="Database" name="database" connectionString="Server=myServerAddress;Database=myDataBase;User=myUsername;Password=myPassword;" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" commandText="INSERT INTO LogTable (Level, Logger, Message, Exception) VALUES (@level, @logger, @message, @exception)"> <parameter name="@date" layout="${longdate}" /> <parameter name="@level" layout="${level}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@message" layout="${message}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <!-- Define the rules --> <rules> <!-- Log everything to file and console --> <logger name="*" minlevel="Trace" writeTo="logfile,logconsole" /> <!-- Log only errors to the database --> <logger name="*" minlevel="Error" writeTo="database" /> </rules> </nlog> |
4.Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
using NLog.Web; var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); // Configure NLog as the logging provider builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); builder.Host.UseNLog(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } catch (Exception ex) { // NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } |
5. Mysql Log Data
![](https://www.auctionpro.co.kr/wp-content/uploads/2024/07/image-8-1024x383.png)
6. Log files
![](https://www.auctionpro.co.kr/wp-content/uploads/2024/07/image-9.png)
1 2 3 4 5 6 7 8 9 10 |
2024-07-10 13:56:04.8714 INFO Starting up 2024-07-10 15:30:18.1394 INFO Starting up 2024-07-10 15:43:03.4143 INFO Starting up 2024-07-10 16:06:03.7546 DEBUG InMemoryCacheCore.Program init main 2024-07-10 16:06:04.6545 INFO InMemoryCacheCore.Program Starting up 2024-07-10 16:22:22.6490 DEBUG InMemoryCacheCore.Program init main 2024-07-10 16:22:23.9055 INFO InMemoryCacheCore.Program Starting up 2024-07-10 16:29:31.8965 DEBUG InMemoryCacheCore.Program init main |