先要配置以下config文件
也可以是任意的xml文件
asp.net 就直接配置web.config文件
提供代码下载:http://www.cnblogs.com/Leodr/archive/2008/07/25/1251299.html (和一个网络文件夹一起的)
具体如下:(注——里面还有一些配置是我做的一个网络文件夹的配置信息,注释很清楚,自己看了。)
Logger类的代码如下:
也可以是任意的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类的代码如下:
using System;
using System.IO;
using System.Diagnostics;
using System.Configuration;
/**/
/// <summary>
/// 纪录跟踪系统错误日至的类.
/// </summary>
public class Logger
{
public const int INFO = 3;
public const int WARN = 2;
public const int ERROR = 1;
public const int ALWAYS = 1;
protected static string strCurrentFilename = "";
protected static TraceSwitch dSwitch = null;
protected static FileStream fsLog = null;
protected static TextWriterTraceListener tlLog = null;
protected static bool bStickInEventLog = false;
public Logger()
{
dSwitch =
new TraceSwitch
("dSwitch", "Application tracing");
Trace.WriteLine("Just created dSwitch: " +
dSwitch.Level);
string strLogDir = System.Web.HttpContext.Current.Server.MapPath("~/") + ConfigurationManager.AppSettings["LogPath"].ToString();
if (!Directory.Exists(strLogDir)) Directory.CreateDirectory(strLogDir);
if (!(strLogDir == null) && !(strLogDir.Equals("")))
{
fsLog = new FileStream(strLogDir,
FileMode.OpenOrCreate);
tlLog = new
TextWriterTraceListener(fsLog);
Trace.Listeners.Add(tlLog);
}
string strEventLog = ConfigurationManager.AppSettings["EventLog"].ToString();
if (!(strLogDir == null) && !(strLogDir.Equals("")))
{
// 是否将日至写入事件查看器
if (strLogDir.ToLower().Equals("true"))
bStickInEventLog = true;
else
bStickInEventLog = false;
}
}
private static TraceSwitch GetTraceSwitch(string sName)
{
TraceSwitch ts = new TraceSwitch(
sName, "Integration Framework tracing");
return ts;
}//end GetTraceSwitch()
private static void SetupTracing()
{
dSwitch = GetTraceSwitch("dSwitch");
Trace.WriteLine("Just created dSwitch: " +
dSwitch.Level);
string strLogDir = System.Web.HttpContext.Current.Server.MapPath("~/") + ConfigurationManager.AppSettings["LogPath"].ToString();
string strLogfile = "";
string strFile = Logger.getCurrentFilename();
if (!Directory.Exists(strLogDir))
Directory.CreateDirectory(strLogDir);
if (strFile.Equals(""))
{
System.DateTime now = System.DateTime.Now;
strLogfile = strLogDir + "\\" +
"RENHEOA" +
now.DayOfYear.ToString() +
"-" +
now.Hour.ToString() +
"-" +
now.Minute.ToString() +
".log";
Logger.setCurrentFilename(strLogfile);
strFile = strLogfile;
}
try
{
// 创建一个用于输出跟踪信息的文件
fsLog = new FileStream
(strFile, FileMode.OpenOrCreate);
if (!fsLog.CanWrite)
{
System.DateTime now = System.DateTime.Now;
strLogfile = strLogDir + "\\" +
"RENHEOA" +
now.DayOfYear.ToString() +
"-" +
now.Hour.ToString() +
"-" +
now.Minute.ToString() +
".log";
Logger.setCurrentFilename(strLogfile);
fsLog = new FileStream
(strFile, FileMode.OpenOrCreate);
}//end if
tlLog = new
TextWriterTraceListener(fsLog);
Trace.Listeners.Add(tlLog);
}
catch (Exception exc)
{
// 出现异常
}//end catch
string strEventLog = ConfigurationManager.AppSettings["EventLog"].ToString();
if (!(strEventLog == null) && !(strEventLog.Equals("")))
{
// 是否将日至写入事件查看器
if (strEventLog.ToLower().Equals("true"))
bStickInEventLog = true;
else
bStickInEventLog = false;
}//end if logfile
}//end SetupTracking()
/**/
/// <summary>
/// 写入跟踪信息到日至文件,
/// </summary>
/// <param name="sSwitchName">创建一个新的TraceSwitch</param>
/// <param name="when">要写入日至的级别</param>
/// <param name="strLogThis">要写入日至的具体信息</param>
/// <returns></returns>
public static void Log(string sSwitchName,
int when,
string strLogThis)
{
if (dSwitch == null) SetupTracing();
//指定自定义的日志权重处理级别
TraceSwitch ts = GetTraceSwitch(sSwitchName);
if (ts == null) ts = GetTraceSwitch("dSwitch");
int nSwLvl = (int)ts.Level;
if (when > nSwLvl) return; // 比预先设定级别重要的信息才会被写入
tlLog.WriteLine(String.Format("[{0}]\t[{1}]\t[{2}]", MyConvert(when), System.DateTime.Now.ToString(),
strLogThis));
tlLog.Flush();
if ((when == Logger.ERROR)
&& bStickInEventLog)
{
if (!EventLog.SourceExists("RENHEOA"))
EventLog.CreateEventSource(
"RENHEOA", "Application");
// 写入日至到事件查看器
System.Diagnostics.EventLog el =
new EventLog("Application");
el.Source = "RENHEOA";
el.WriteEntry(strLogThis,
System.Diagnostics.EventLogEntryType.Error);
el.Close();
}
return;
}//end log(str,int,str)
/**/
/// <summary>
/// 写入跟踪信息到日至文件,
/// </summary>
/// <param name="when">要写入日至的级别</param>
/// <param name="strLogThis">要写入日至的具体信息</param>
/// <returns></returns>
public static void Log(int when, string strLogThis)
{
if (dSwitch == null) SetupTracing();
int nSwitchLevel = (int)dSwitch.Level;
if (when > nSwitchLevel) return;
tlLog.WriteLine(String.Format("[{0}]\t[{1}]\t[{2}]", MyConvert(when), System.DateTime.Now.ToString(),
strLogThis));
tlLog.Flush();
if ((when == Logger.ERROR)
&& bStickInEventLog)
{
if (!EventLog.SourceExists("RENHEOA"))
EventLog.CreateEventSource("RENHEOA",
"Application");
// 写入日至到事件查看器
System.Diagnostics.EventLog el =
new EventLog("Application");
el.Source = "RENHEOA";
el.WriteEntry(strLogThis);
el.Close();
}//
return;
}//end log(int,string)
/**/
/// <summary>
/// 写入跟踪信息到日至文件,
/// </summary>
/// <param name="strLogThis">要写入日至的具体信息</param>
/// <returns></returns>
public static void Log(string strLogThis)
{
if (dSwitch == null) SetupTracing();
tlLog.WriteLine(String.Format("[{0}]/t[{1}]/t[{2}]", "其他信息", System.DateTime.Now.ToString(),
strLogThis));
tlLog.Flush();
return;
}//end log(int,string)
protected static string getCurrentFilename()
{
lock (typeof(Logger))
{
return Logger.strCurrentFilename;
}
}
protected static void setCurrentFilename(string sIn)
{
lock (typeof(Logger))
{
Logger.strCurrentFilename = sIn;
}
}
/**/
/* csdn 网友提供方法,测试可用 */
/**/
/ <summary>
/ 将出错信息写入到日志文件中并以当天日期命名文件
/ </summary>
/ <param name="err"></param>
//public static void WriteTxtLog(string err)
//{
// try
// {
// string a = Application.StartupPath + @"\Log\Log" + System.DateTime.Now.Date.ToLongDateString() + ".txt";
// string DirPath = Application.StartupPath + @"\Log";
// if (!File.Exists(a))
// {
// if (!Directory.Exists(DirPath))
// {
// Directory.CreateDirectory(DirPath);
// }
// FileInfo fi = new FileInfo(a);
// }
// StreamWriter w = File.AppendText(a);
// w.WriteLine(System.DateTime.Now + "\r\n" + err + "\r\n");
// w.Close();
// }
// catch (Exception e)
// {
// Tools.ShowMessage(e.ToString(), MessageBoxIcon.Information);
// }
//}
public static string MyConvert(int when)
{
switch (when)
{
case 1: return "Error";
case 2: return "Warning";
case 3: return "Info";
default: return "ALL";
}
}
}//end class
原文连接:
http://www.cnblogs.com/Leodr/archive/2008/07/25/1251266.html