[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); } } } } |
'C#' 카테고리의 다른 글
[C#] Interop 한 Excel API 가 정상적으로 종료 되지 않을 때 처리 방안 (0) | 2024.09.03 |
---|---|
PdfSharp을 이용한 Tiff To Pdf 변환 예제 (0) | 2024.06.16 |
BitMiracle.Docotic.Pdf를 이용한 Tiff To Pdf 변환 예제 (0) | 2024.06.16 |
[C#] HttpClient.PostAsync 메서드 에는 HttpCompletionOption을 설정 할 수 없는 부분에 대한 대처 방안 (0) | 2024.02.04 |
[C#] HttpClient 에 CookieContainer 이용 JSESSIONID 설정 진행 예제 (0) | 2024.02.04 |