本文实例讲述了C#实现将程序运行信息写入日志的方法。分享给大家供大家参考。具体如下:
1.LogManager类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
class LogManager { static object locker = new object (); /// <summary> /// 重要信息写入日志 /// </summary> /// <param name="logs">日志列表,每条日志占一行</param> public static void WriteProgramLog( params string [] logs) { lock (locker) { string LogAddress = Environment.CurrentDirectory + "\\Log" ; if (!Directory.Exists(LogAddress + "\\PRG" )) { Directory.CreateDirectory(LogAddress + "\\PRG" ); } LogAddress = string .Concat(LogAddress, "\\PRG\\" , DateTime.Now.Year, '-' , DateTime.Now.Month, '-' , DateTime.Now.Day, "_program.log" ); StreamWriter sw = new StreamWriter(LogAddress, true ); foreach ( string log in logs) { sw.WriteLine( string .Format( "[{0}] {1}" , DateTime.Now.ToString(), log)); } sw.Close(); } } } |
2.调用方法
3.运行结果
希望本文所述对大家的C#程序设计有所帮助。