프로그래밍/C#

[C#] Log4net을 이용한 Logger 구현

흔한티벳여우 2023. 4. 18. 10:47
반응형

일단 nuget에서 log4net을 설치한다.

 

LogMaster.cs

public enum LogType
{
    INFO,
    DEBUG,
    ERROR,
    ALL
}

public class LogData
{
    public DateTime TimeStamp { get; set; }
    public string Date
    {
        get { return TimeStamp.ToString("yyyy-MM-dd"); }
    }
    public string Time
    {
        get { return TimeStamp.ToString("HH:mm:ss.fff"); }
    }
    public LogType LogType { get; set; }
    public string StrLogType
    {
        get { return LogType.ToString(); }
    }
    public string Log { get; set; }
}

public sealed class LogMaster
{
    private static readonly LogMaster _instance = new LogMaster();
    private ILog _log = LogManager.GetLogger("Loger");

    public static LogMaster GetInstance() { return _instance; }
    public string _path;

    private LogMaster()
    {

    }
    public void SetLogPath(string path)
    {
        _path = path;
    }
    public void LogConfig()
    {
        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

        PatternLayout patternLayout = new PatternLayout();
        patternLayout.ConversionPattern = "%message%newline";
        patternLayout.ActivateOptions();

        RollingFileAppender roller = new RollingFileAppender();
        roller.Name = "Loger";
        //string filePath = $"{Type}\\{JACKUP_LINE.ToString()}\\";
        //roller.File = @"c:\SpreadingLog\";
        roller.File = _path;
        roller.RollingStyle = RollingFileAppender.RollingMode.Date;
        roller.MaxSizeRollBackups = 10;
        roller.StaticLogFileName = false;
        roller.DatePattern = "yyyyMMdd'.txt'";
        roller.AppendToFile = true;
        roller.Layout = patternLayout;

        roller.ActivateOptions();
        hierarchy.Root.AddAppender(roller);

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

    public void WriteLog(string message, LogType type = LogType.INFO)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        sb.Append($" [{type.ToString()}] ");
        sb.Append(message);

        switch (type)
        {
            case LogType.INFO: _log.Info(sb.ToString()); break;
            case LogType.DEBUG: _log.Debug(sb.ToString()); break;
            case LogType.ERROR: _log.Error(sb.ToString()); break;
        }
    }

    public List<LogData> GetLog(DateTime from, DateTime to)
    {
        List<string> lines = new List<string>();
        List<LogData> logDatas = new List<LogData>();
        Clear();
        for (DateTime date = from; date <= to; date = date.AddDays(1))
        {
            string fileName = date.ToString("yyyyMMdd") + ".txt";
            if (File.Exists(_path + fileName))
            {
                lines.AddRange(File.ReadLines(_path + fileName).ToList());
            }
        }
        LogConfig();

        if (lines.Count != 0)
        {
            foreach (var it in lines)
            {
                string[] rawData = it.Split(' ');
                if (rawData.Length < 2)
                {
                    continue;
                }
                DateTime time = DateTime.ParseExact(rawData[0] + " " + rawData[1], "yyyy-MM-dd HH:mm:ss.fff", null);
                string strLogType = rawData[2].Replace("[", "");
                strLogType = strLogType.Replace("]", "");
                LogType logType = (LogType)Enum.Parse(typeof(LogType), strLogType);

                StringBuilder sb = new StringBuilder();
                for (int i = 3; i < rawData.Length; i++)
                {
                    sb.Append(rawData[i] + " ");
                }
                logDatas.Add(new LogData()
                {
                    TimeStamp = time,
                    LogType = logType,
                    Log = sb.ToString()
                });
            }
        }
        return logDatas;
    }

    public void Clear()
    {
        _log.Logger.Repository.ResetConfiguration();
    }
}

 

초기 설정

LogMaster log = LogMaster.GetInstance();
log.SetLogPath(System.IO.Directory.GetCurrentDirectory() + @"\Log\");
log.Clear();
log.LogConfig();

 

사용할 때

var json = JsonConvert.SerializeObject(value, Formatting.None);
LogMaster.GetInstance().WriteLog(" > " + json, LogType.DEBUG);

 

반응형