⚡ Simple Demo to Add NLog to ASP.NET Core Application

1️⃣ Preparing

Logger service cung cấp 4 phương thức ghi log chính:

MethodDescription
InfoGhi log thông tin
DebugGhi log debug
WarningGhi log warning
ErrorGhi log lỗi

💡 Lưu ý: Bạn cần cài NuGet package:

NLog.Extensions.Logging


2️⃣ Trong Class Library

2.1 Xây dựng Interface ILoggerManager

public interface ILoggerManager
{
    void LogInfo(string message);
    void LogWarn(string message);
    void LogDebug(string message);
    void LogError(Exception ex, string message = null);
}

2.2 Triển khai LoggerManager

public class LoggerManager : ILoggerManager
{
    private static ILogger logger = LogManager.GetCurrentClassLogger();

    public LoggerManager()
    {
    }

    public void LogDebug(string message)
    {
        logger.Debug(message);
    }

    public void LogError(Exception ex, string message = null)
    {
        logger.Error(ex, message);
    }

    public void LogInfo(string message)
    {
        logger.Info(message);
    }

    public void LogWarn(string message)
    {
        logger.Warn(message);
    }
}


3️⃣ Trong Ứng dụng ASP.NET Core

3.1 Thêm file NLog.config

File cấu hình NLog.config:

<?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"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="d:\Projects\CompanyEmployees\Project\internal_logs\internallog.txt">

    <targets>
        <target name="logfile" xsi:type="File"
                fileName="C:\Users\Tim\Desktop\dev\common\dotnet\Source\NLogDemo\NLogDemo\${shortdate}_log.txt"
                layout="${longdate} ${level:uppercase=true} ${message}"/>
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

💡 Giải thích:

  • minlevel="Debug" → Log level mặc định là Debug
  • fileName → File log sẽ lưu ở đâu và tên file format như thế nào

3.2 Load NLog trong Startup.cs

public Startup(IConfiguration configuration)
{
    LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
    Configuration = configuration;
}


3.3 Đăng ký Service Logger

Trong ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddScoped<ILoggerManager, LoggerManager>();
}


4️⃣ Ví dụ sử dụng Logger trong ASP.NET Core

namespace NLogDemo.Pages
{
    public class IndexModel : PageModel
    {
        private ILoggerManager _logger;

        public IndexModel(ILoggerManager logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            _logger.LogInfo("Log information"); 
            _logger.LogDebug("Log debug"); 
            _logger.LogWarn("Log warning");

            var ex = new InvalidCastException();
            _logger.LogError(ex, "Log Error");
        }
    }
}

💡 Giải thích:

  • Khi trang Index được load, các log sẽ được ghi theo từng mức độ.
  • File log sẽ được lưu theo cấu hình trong NLog.config.