C#写日志两个简单方法

在开发,有时为了验证程序运行是否正确,通常要写日志来记录操作,在一个日志类里,通常有两个方法:


方法一:以日期为日志文件名

public void WriteLog(string msg)
{
    string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }
    string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    try
    {
        using (StreamWriter sw = File.AppendText(logPath))
        {
            sw.WriteLine("消息:" + msg);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
    catch (IOException e)
    {
        using (StreamWriter sw = File.AppendText(logPath))
        {
            sw.WriteLine("异常:" + e.Message);
            sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
            sw.WriteLine("**************************************************");
            sw.WriteLine();
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
    }
}

方法二:以文档名称和日期结合作为文件名

public void WriteLog(string documentName, string msg)
{
    string errorLogFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
    if (!System.IO.Directory.Exists(errorLogFilePath))
    {
        System.IO.Directory.CreateDirectory(errorLogFilePath);
    }
    string logFile = System.IO.Path.Combine(errorLogFilePath, documentName + "@" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt");
    bool writeBaseInfo = System.IO.File.Exists(logFile);
    StreamWriter swLogFile = new StreamWriter(logFile, true, Encoding.Unicode);
    swLogFile.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + msg);
    swLogFile.Close();
    swLogFile.Dispose();
}


你可能感兴趣的:(C#写日志两个简单方法)