C# 基础 - 日志捕获一使用 StreamWriter

public static class LogHelper
{
    private static readonly string _baseDir = AppDomain.CurrentDomain.BaseDirectory +  "VILog";
    private static DateTime _currentDate;
    private static StreamWriter _sw;

    static LogHelper()
    {
        DirectoryInfo di = new DirectoryInfo(_baseDir);
        if (!di.Exists)
            di.Create();
    }

    private static void CheckLogFile()
    {
        if (_sw == null)
        {
            _currentDate = DateTime.Now.Date;
            _sw = new StreamWriter(string.Format(_baseDir + "/{0}.{1}-{2}-{3}.log", Process.GetCurrentProcess().ProcessName, _currentDate.Year, _currentDate.Month, _currentDate.Day), true, Encoding.UTF8);
            return;
        }

        DateTime dt = DateTime.Now.Date;
        if (DateTime.Compare(dt, _currentDate) != 0)
        {
            _sw.Close();
            _sw = null;
            _currentDate = dt;
            CheckLogFile();
        }
    }

    public static void Log(string str, object sender = null, LogLevel level = LogLevel.Info, string detail = null)
    {
        if (IsStopLog) return;

        CheckLogFile();

        if (string.IsNullOrEmpty(str)) return;

        _sw.WriteLine("[{0}.{1}]:[{2}]{3}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), level, str);

        if (!string.IsNullOrEmpty(detail))
            _sw.WriteLine("Detail:{0}", detail);

        _sw.Flush();
    }

    public static void Info(string str, object sender = null, string detail = null)
    {
        Log(str, sender, LogLevel.Info, detail);
    }

    public static void Error(string str, object sender = null, string detail = null)
    {
        Log(str, sender, LogLevel.Error, detail);
    }

    public static void Error(string str, object sender = null, Exception ex = null)
    {
        string errmsg = ex.StackTrace?.ToString();

        Log(str, sender, LogLevel.Error, Environment.NewLine + errmsg);
    }

    public static void Warning(string str, object sender = null, string detail = null)
    {
        Log(str, sender, LogLevel.Warning, detail);
    }

    public static bool IsStopLog { get; set; }
}

public enum LogLevel
{
    Info,
    Error,
    Warning
}
posted @ 2021-03-03 19:45  鑫茂  阅读(110)  评论(0编辑  收藏  举报