我自己经常用的,发出来大家共同学习
先要配置以下config文件
也可以是任意的xml文件
asp.net 就直接配置web.config文件
提供代码下载:http://www.cnblogs.com/Leodr/archive/2008/07/25/1251299.html (和一个网络文件夹一起的)
具体如下:(注——里面还有一些配置是我做的一个网络文件夹的配置信息,注释很清楚,自己看了。)
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<!--日志权重处理级别
0 Off 不输出跟踪和调试消息。
1 Error 输出错误处理消息。
2 Warning 输出警告和错误处理消息。
3 Info 输出信息性消息、警告和错误处理消息。
4 Verbose 输出所有调试和跟踪消息。
-->
<switches>
<add name="dSwitch" value="4"/>
<!-- 默认权重处理级别 -->
<add name="sdfs" value="2"/>
</switches>
<trace autoflush="true" indentsize="2"/>
</system.diagnostics>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=RJB-ZYB;Initial Catalog=RenheOA2;User ID=sa"/>
</connectionStrings>
<appSettings>
<!-- 日至文件路径 -->
<add key="LogPath" value="logdir"/>
<!-- 日至是否写入事件查看器 -->
<add key="EventLog" value="true"/>
<!-- 共享文件夹默认目录-->
<add key="folderPath" value="Upload"/>
<!--上传文件类型-->
<add key="FileTypeLimit" value=".zip,.rar,.jpg,.gif,.bmp,.doc,.txt,.swf,.xls,.doc,.ppt"/>
<!--限制文件夹的总大小,单位为KB,102400KB=100M-->
<add key="FolderSizeLimit" value="40960"/>
</appSettings>
<system.web>
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20"/>
<!-- 上传大文件设置-->
<httpRuntime executionTimeout="90" maxRequestLength="102400" useFullyQualifiedRedirectUrl="false"
minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100"/>
<authentication mode="Windows"/>
<!--
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<compilation debug="true" />
</system.web>

</configuration>
Logger类的代码如下。
1
using System;
2
using System.IO;
3
using System.Diagnostics;
4
using System.Configuration;
5
6
/**////---------------------------------------
7
// Copyright (c) 2008 Liu Yi,
8
// leodr.cnbolgs.com
9
/**////---------------------------------------
10
namespace LEO.Common
11

{
12
/**//// <summary>
13
/// 纪录跟踪系统错误日至的类.
14
/// </summary>
15
public class Logger
16
{
17
public const int INFO = 3;
18
public const int WARN = 2;
19
public const int ERROR= 1;
20
public const int ALWAYS=1;
21
22
protected static string strCurrentFilename = "";
23
protected static TraceSwitch dSwitch = null;
24
protected static FileStream fsLog = null;
25
protected static TextWriterTraceListener tlLog = null;
26
protected static bool bStickInEventLog = false;
27
28
public Logger()
29
{
30
dSwitch =
31
new TraceSwitch
32
("dSwitch","Application tracing");
33
Trace.WriteLine("Just created dSwitch: " +
34
dSwitch.Level);
35
36
string strLogDir = System.Web.HttpContext.Current.Server.MapPath("~/") + ConfigurationManager.AppSettings["LogPath"].ToString();
37
if (!Directory.Exists(strLogDir)) Directory.CreateDirectory(strLogDir);
38
39
if( !(strLogDir==null) && !(strLogDir.Equals("")))
40
{
41
42
fsLog = new FileStream(strLogDir,
43
FileMode.OpenOrCreate);
44
tlLog = new
45
TextWriterTraceListener(fsLog);
46
Trace.Listeners.Add(tlLog);
47
}
48
49
string strEventLog = ConfigurationManager.AppSettings["EventLog"].ToString();
50
if( !(strLogDir==null) && !(strLogDir.Equals("")))
51
{
52
// 是否将日至写入事件查看器
53
if(strLogDir.ToLower().Equals("true"))
54
bStickInEventLog = true;
55
else
56
bStickInEventLog = false;
57
}
58
59
}
60
61
private static TraceSwitch GetTraceSwitch(string sName)
62
{
63
TraceSwitch ts = new TraceSwitch(
64
sName, "Integration Framework tracing");
65
return ts;
66
}//end GetTraceSwitch()
67
68
private static void SetupTracing()
69
{
70
dSwitch = GetTraceSwitch("dSwitch");
71
Trace.WriteLine("Just created dSwitch: " +
72
dSwitch.Level);
73
string strLogDir = System.Web.HttpContext.Current.Server.MapPath("~/") + ConfigurationManager.AppSettings["LogPath"].ToString();
74
string strLogfile = "";
75
string strFile = Logger.getCurrentFilename();
76
77
if (!Directory.Exists(strLogDir))
78
Directory.CreateDirectory(strLogDir);
79
80
if(strFile.Equals(""))
81
{
82
System.DateTime now = System.DateTime.Now;
83
strLogfile = strLogDir + "\\" +
84
"RENHEOA" +
85
now.DayOfYear.ToString() +
86
"-" +
87
now.Hour.ToString() +
88
"-" +
89
now.Minute.ToString() +
90
".log";
91
Logger.setCurrentFilename(strLogfile);
92
strFile = strLogfile;
93
}
94
95
try
96
{
97
// 创建一个用于输出跟踪信息的文件
98
fsLog = new FileStream
99
(strFile,FileMode.OpenOrCreate);
100
if( !fsLog.CanWrite )
101
{
102
System.DateTime now = System.DateTime.Now;
103
strLogfile = strLogDir + "\\" +
104
"RENHEOA" +
105
now.DayOfYear.ToString() +
106
"-" +
107
now.Hour.ToString() +
108
"-" +
109
now.Minute.ToString() +
110
".log";
111
Logger.setCurrentFilename(strLogfile);
112
fsLog = new FileStream
113
(strFile,FileMode.OpenOrCreate);
114
}//end if
115
116
tlLog = new
117
TextWriterTraceListener(fsLog);
118
Trace.Listeners.Add(tlLog);
119
}
120
catch(Exception exc)
121
{
122
// 出现异常
123
124
}//end catch
125
126
string strEventLog = ConfigurationManager.AppSettings["EventLog"].ToString();
127
if( !(strEventLog==null) && !(strEventLog.Equals("")))
128
{
129
// 是否将日至写入事件查看器
130
if(strEventLog.ToLower().Equals("true"))
131
bStickInEventLog = true;
132
else
133
bStickInEventLog = false;
134
}//end if logfile
135
136
}//end SetupTracking()
137
138
139
/**//// <summary>
140
/// 写入跟踪信息到日至文件,
141
/// </summary>
142
/// <param name="sSwitchName">创建一个新的TraceSwitch</param>
143
/// <param name="when">要写入日至的级别</param>
144
/// <param name="strLogThis">要写入日至的具体信息</param>
145
/// <returns></returns>
146
public static void Log( string sSwitchName,
147
int when,
148
string strLogThis)
149
{
150
if(dSwitch == null) SetupTracing();
151
152
//指定自定义的日志权重处理级别
153
TraceSwitch ts = GetTraceSwitch(sSwitchName);
154
if (ts == null) ts = GetTraceSwitch("dSwitch");
155
int nSwLvl = (int) ts.Level;
156
if(when > nSwLvl) return; // 比预先设定级别重要的信息才会被写入
157
158
tlLog.WriteLine(String.Format("[{0}]\t[{1}]\t[{2}]", MyConvert(when), System.DateTime.Now.ToString(),
159
strLogThis));
160
tlLog.Flush();
161
162
if( (when == Logger.ERROR)
163
&& bStickInEventLog)
164
{
165
if (!EventLog.SourceExists("RENHEOA"))
166
EventLog.CreateEventSource(
167
"RENHEOA", "Application");
168
// 写入日至到事件查看器
169
System.Diagnostics.EventLog el =
170
new EventLog("Application");
171
el.Source = "RENHEOA";
172
el.WriteEntry(strLogThis,
173
System.Diagnostics.EventLogEntryType.Error);
174
el.Close();
175
}
176
return;
177
178
179
}//end log(str,int,str)
180
181
182
/**//// <summary>
183
/// 写入跟踪信息到日至文件,
184
/// </summary>
185
/// <param name="when">要写入日至的级别</param>
186
/// <param name="strLogThis">要写入日至的具体信息</param>
187
/// <returns></returns>
188
public static void Log(int when, string strLogThis)
189
{
190
if(dSwitch == null) SetupTracing();
191
192
int nSwitchLevel = (int) dSwitch.Level;
193
if(when > nSwitchLevel) return;
194
195
tlLog.WriteLine(String.Format("[{0}]\t[{1}]\t[{2}]",MyConvert(when),System.DateTime.Now.ToString(),
196
strLogThis));
197
tlLog.Flush();
198
199
if ((when == Logger.ERROR)
200
&& bStickInEventLog)
201
{
202
if (!EventLog.SourceExists("RENHEOA"))
203
EventLog.CreateEventSource("RENHEOA",
204
"Application");
205
// 写入日至到事件查看器
206
System.Diagnostics.EventLog el =
207
new EventLog("Application");
208
el.Source = "RENHEOA";
209
el.WriteEntry(strLogThis);
210
el.Close();
211
}//
212
return;
213