1.日志文件是winform自己的,不是windows的,后缀还是log 2.比如在执行完一个方法后,调用日志的写的方法,写入指定的内容。
在 Program.cs 里面定义一个方法,参数根据需要自己定义
public static void WriteLog(string param1, string param2)
{
System.IO.File.AppendAllText(
logFileName, // 日志文件名
string.Format("{0}\t{1}\t{2}", DateTime.Now, param1, param2), // 用制表符 \t 分隔字段
Encoding.Default);
}
调用的时候:
Program.WriteLog("添加", "添加的内容");
public class Log
{
private static readonly object obj = new object();
/// <summary>
/// 操作日志
/// </summary>
/// <param name="s">日志能容</param>
public static void WriteLog(string title,string content)
{
WriteLogs(title, content, "操作日志");
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="s">日志内容</param>
public static void WriteError(string title,string content)
{
WriteLogs(title, content, "错误日志");
}
public static void WriteLogs(string title, string content, string type)
{
lock (obj)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
if (!string.IsNullOrEmpty(path))
{
path = AppDomain.CurrentDomain.BaseDirectory + "log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyMM");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("dd") + ".txt";
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now + " " + title);
sw.WriteLine("日志类型:" + type);
sw.WriteLine("详情:" + content);
sw.WriteLine("----------------------------------------");
sw.Close();
}
}
}
}
}
.net里有一个eventlog控件,这个就像写系统日志一样。frmLog是控件名称
1
frmLog.WriteEntry(message +
","
+ DateTime.Now.ToString());
当然自己也可以写txt或xml文件。
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public
void
WritelogTxt(
string
user,
string
msg)
{
if
(!File.Exists(
"..\\..\\LogFile.txt"
))
{
File.CreateText(
"..\\..\\LogFile.txt"
);
}
FileInfo finfo =
new
FileInfo(
"..\\..\\LogFile.txt"
);
if
(finfo.Exists && finfo.Length > 2048 * 10240)
{
finfo.Delete();
}
try
{
FileStream fs =
new
FileStream(
"..\\..\\LogFile.txt"
, FileMode.Append);
StreamWriter strwriter=
new
StreamWriter(fs);
try
{
DateTime d=DateTime.Now;
strwriter.WriteLine(user+
","
+msg+
","
+d.ToString());
//strwriter.Flush();
}
catch
(Exception ee)
{
Console.WriteLine(
"日志文件写入失败信息:"
+ee.ToString());
}
finally
{
strwriter.Close();
strwriter=
null
;
fs.Close();
fs=
null
;
}
}
catch
(Exception ee)
{
Console.WriteLine(ee.ToString());
}
}
public
string
[] ReadLogTxt()
{
if
(File.Exists(
"..\\..\\LogFile.txt"
))
{
StreamReader sr = File.OpenText(
"..\\..\\LogFile.txt"
);
string
[] txt = sr.ReadToEnd().Split(
'\n'
);
sr.Close();
return
txt;
}
else
return
null
;
}
1386

被折叠的 条评论
为什么被折叠?



