From 5235dde103124f973102dd9f6eca4465f53718c0 Mon Sep 17 00:00:00 2001 From: wy <1qaz@123> Date: 星期一, 26 九月 2022 21:19:05 +0800 Subject: [PATCH] nothing --- WebAPI/LogService.cs | 73 ++++++++++++++++++++++++++++++++++++ 1 files changed, 73 insertions(+), 0 deletions(-) diff --git a/WebAPI/LogService.cs b/WebAPI/LogService.cs new file mode 100644 index 0000000..7762f83 --- /dev/null +++ b/WebAPI/LogService.cs @@ -0,0 +1,73 @@ +锘縰sing Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WebAPI +{ + public class LogService + { + private static readonly object lockObj = new object(); + + public static void WriteAsync(object obj, string filePath = "Vlog", bool isAppend = true) + { + Task.Run(() => + { + Write(obj, filePath, isAppend); + }); + } + + public static void WriteAsync<T>(object obj, string filePath = "Vlog", bool isAppend = true) + { + Task.Run(() => + { + Write(obj, $@"{filePath}\{typeof(T).Name}", isAppend); + }); + } + + #region 鏃ュ織 + public static void Write(object obj, string filePath = "Vlog", bool isAppend = true) + { + try + { + lock (lockObj) + { + filePath = $@"{filePath}\webapi{DateTime.Now.ToString("yyyyMMdd")}.txt"; + + filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + + if (!System.IO.Directory.Exists(Path.GetDirectoryName(filePath))) + { + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(filePath)); + } + + bool fileExists = System.IO.File.Exists(filePath); + //涓嶅瓨鍦� 鍒欏垱寤鸿鏂囦欢 + if (!fileExists) + { + System.IO.File.Create(filePath).Close(); + } + + using (StreamWriter writer = new StreamWriter(filePath, isAppend)) + { + //瀛樺湪鐨勬椂鍊欐墠鍐欎竴琛� + if (fileExists && isAppend) + { + writer.WriteLine(); + } + + var content = obj is string ? obj : JsonConvert.SerializeObject(obj); + writer.WriteLine($"{DateTime.Now} {content}"); + } + } + } + catch (Exception ex) + { + } + } + #endregion + } +} -- Gitblit v1.9.1