Cấu hình log4net và logging.adapter trong code c#

Cấu hình log4net và common.logging.adapter trong code c#? Đôi khi bạn cần phải config log4net hay common.logging.adapter trong code behind thay vì config trong file app.config; Khi đó sau đây là một giải pháp.

Configure log4net common.logging in code behind

Như một số bài trước đã đề cập, đôi khi chúng ta cần xây dựng một ứng dụng chỉ cần duy nhất một file *.exe; Khi đó việc dùng ILMerge là một giải pháp để gộp các dll vào file exe; Nhưng một số thành phần ở file *.exe.config thì không thể gộp được. Vì vậy, thay các config trong file *.exe.config bằng code trong code behind là một gải pháp. Và sau đây là cách thay việc config log4net và common.logging.adapter trong app.config bằng code c#.

Config cho log4net.
LoggingConfiguration.cs

using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;

namespace LoggingConfiguration
{
    internal static class LogConfiguration
    {
        internal static void SetupLog4net()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            var rollingAppender = GetRollingAppender();
            var consoleAppender = GetConsoleAppender();

            hierarchy.Root.AddAppender(consoleAppender);
            hierarchy.Root.AddAppender(rollingAppender);

            hierarchy.Root.Level = Level.Debug;
            hierarchy.Configured = true;

            var logger = LogManager.GetLogger(typeof(LogConfiguration));
            logger.Info($"Init Log4net successfully.");
        }

        private static ConsoleAppender GetConsoleAppender()
        {
            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "[%-40.60logger{3}] - %message%newline";
            patternLayout.ActivateOptions();

            var consoler = new ConsoleAppender();
            consoler.Layout = patternLayout;
            consoler.Threshold = Level.Info;
            return consoler;
        }

        private static RollingFileAppender GetRollingAppender()
        {
            var patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "[%date{yyyy-MM-dd HH:mm:ss.fff}] [%-5level] [%-60.60logger{3}] - %message%newline";
            patternLayout.ActivateOptions();

            var roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = @"Logs\Log4net.log";
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "2MB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            return roller;
        }
    }
}

Cách dùng.
Program.cs

using log4net;
using System;

namespace LoggingConfiguration
{
    class Program
    {
        static void Main(string[] args)
        {
            LogConfiguration.SetupLog4net();

            var logger = LogManager.GetLogger(typeof(Program));

            logger.Info("Wellcome to logging configuration.");
            Console.ReadKey();
        }
    }
}

Config cho common.logging.adapter.
LoggingConfiguration.cs

internal static void SetupCommonLogging()
{
    var commonLoggingConfig = new Common.Logging.Configuration.NameValueCollection();
    commonLoggingConfig["configType"] = "EXTERNAL";

    var adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(commonLoggingConfig);
    Common.Logging.LogManager.Adapter = adapter;

    var logger = Common.Logging.LogManager.GetLogger(typeof(LogConfiguration));
    logger.Info($"[SetupLog4net] Init common.logging successfully.");
}

Lưu ý

Phần configType chúng ta chỉ được sử dụng EXTERNAL. Vì tùy chọn này cho common.logging.adapter biết phần config sẽ có thể là config file hoặc code hoặc bất kỳ đâu. Khi đó common.logging.adapter sẽ lấy config của log4net. Nếu bạn chọn là FILE/FILE-WATCH/INLINE thì bạn sẽ không thể log bằng common.logging vì common.logging.adapter sẽ không thể tìm thấy phần config cho nó ở app.config hay một file khác do bạn chỉ định. Hoặc nếu bạn chọn cách không config gì cả thì việc log ra file bằng common.logging là bình thường nhưng khi log ra Console thì sẽ bị trùng nội dung. Xem thêm tại đây phần 1.4.4.

Cách dùng.
Program.cs

static void Main(string[] args)
{
    LogConfiguration.SetupLog4net();
    LogConfiguration.SetupCommonLogging();

    var logger = LogManager.GetLogger(typeof(Program));

    logger.Info("Wellcome to logging configuration.");
    Console.ReadKey();
}

Đừng quên, để sử dụng được những dòng code trên, project của bạn phải cài đủ Nuget packages như bênh dưới.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Common.Logging" version="3.3.1" targetFramework="net46" />
  <package id="Common.Logging.Core" version="3.3.1" targetFramework="net46" />
  <package id="Common.Logging.Log4Net1213" version="3.3.1" targetFramework="net46" />
  <package id="log4net" version="2.0.3" targetFramework="net46" />
</packages>

Bạn có thể tải về code tham khảo tại đây.

Source code

Phạm Tuân

Visual Studio Code - Bộ text-editor đa năng
Tạo Facebook App trong 1 phút - new version
Mã OTP Hoạt Động Thế Nào Và Cách Tạo Mã OTP
Hãy bình luận trực tiếp ở đây để được trả lời nhanh hơn. 1 bình luận.
  1. I’m impressed, I must say. Actually hardly ever do I encounter a weblog that’s both educative and entertaining, and let me inform you, you may have hit the nail on the head. Your thought is outstanding; the issue is something that not enough persons are talking intelligently about. I am very completely happy that I stumbled throughout this in my search for something referring to this.

Trả lời