c#写日志


方法一:以日期为日志文件名,输出txt文件

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(); 
        } 
    } 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM