C# 日志操作帮助类,控制多线程写入,锁日志

C# 日志操作帮助类,控制多线程写入,锁日志

猿掌柜
2023-07-25 / 0 评论 / 64 阅读 / 正在检测是否收录...

代码如下参考
可修改为自己需要的,这个是每小时创建一个文件

namespace jycurrent.Common
{
    internal class LogsHelper
    {
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
        public enum LogType : int
        {
            DEBUG = 0,
            INFO = 1,
            ERROR = 2
        }
        public static void WriteLogs(string fileName, LogType type, string content)
        {
            try
            {
                LogWriteLock.EnterWriteLock();
                string path = AppDomain.CurrentDomain.BaseDirectory + "\\Log";
                if (!string.IsNullOrEmpty(path))
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + fileName;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH") + ".log";
                    if (!File.Exists(path))
                    {
                        FileStream fs = File.Create(path);
                        fs.Close();
                    }
                    if (File.Exists(path))
                    {
                        using (FileStream file = new FileStream(path, FileMode.Append, FileAccess.Write))
                        {
                            using (StreamWriter sw = new StreamWriter(file))
                            {
                                sw.WriteLine("日志类型:{0}", type == LogType.DEBUG ? "调试日志" : (type == LogType.INFO ? "系统信息" : "错误日志"));
                                sw.WriteLine("日志时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                sw.WriteLine("日志信息:{0}", content);
                                sw.WriteLine("-----------------------------------------------------------\n");
                                sw.Dispose();
                            }
                            file.Close();
                        }
                        //StreamWriter sw = new StreamWriter(path, true, Encoding.Default);
                        //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + type + ":---->" + content);
                        ////  sw.WriteLine("----------------------------------------");
                        //sw.Close();
                    }
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }

        }
    }
}
3

评论 (0)

取消