New file |
| | |
| | | using Newtonsoft.Json; |
| | | using System; |
| | | using System.Collections.Generic; |
| | | using System.IO; |
| | | using System.Linq; |
| | | using System.Text; |
| | | using System.Threading.Tasks; |
| | | |
| | | namespace DAL |
| | | { |
| | | 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 |
| | | } |
| | | } |