본문 바로가기
C#

[C#] Singletone Instance 생성을 이용한 Log File Write 처리 예제 입니다.

by Hwoarang757 2024. 8. 5.
[C#] Singletone Instance 생성을 이용한 Log File Write 처리 예제 입니다.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace GmSFaxAgentWpf.Commons
{
    public class CommonUtils
    {
        private static readonly Lazy<CommonUtils> commonUtils = new Lazy<CommonUtils>(() => new CommonUtils());
        private object lockObj = new object();
        public static CommonUtils Instance { get => commonUtils.Value; }
 
        private CommonUtils()
        {
 
        }
 
 
        public void WriteLog(string methodName,string logStr)
        {
               
            try
            {
                lock (lockObj)
                {
                    string logDir = $@"{Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\log";
                    if (!Directory.Exists(logDir))
                        Directory.CreateDirectory(logDir);
 
                    string logFile = $@"{logDir}\{DateTime.Now:yyyyMMdd}.log";
 
                    using (FileStream fileStream = new FileStream(logFile, FileMode.Append))
                    using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default))
                    {
                        streamWriter.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}][{methodName}][INFO] - {logStr}");
 
                        streamWriter.Close();
                        fileStream.Close();
                    }
                }
 
            } catch(Exception exception)
            {
                Debug.WriteLine(exception);
            }
        }
 
        public void WriteLog(string methodName, Exception exception)
        {
            try
            {
                lock (lockObj)
                {
                    string logDir = $@"{Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\log";
                    if (!Directory.Exists(logDir))
                        Directory.CreateDirectory(logDir);
 
                    string logFile = $@"{logDir}\{DateTime.Now:yyyyMMdd}.log";
 
                    using (FileStream fileStream = new FileStream(logFile, FileMode.Append))
                    using (StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default))
                    {
                        streamWriter.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}][{methodName}][ERROR] - {exception}");
 
                        streamWriter.Close();
                        fileStream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
 
        }
 
    }
}