1.新建一个文件夹存放LOG文件,我建的文件夹为logs,保证这个文件具有写入的权限.
2.新建一个类:Clogs.cs
private StreamWriter swWrite = null;//写文件
private string logpath = null;//日志路径
/// <summary>
/// 判断是否有当天日志,如果没有则创建
/// </summary>
/// <param name="sCurDate">日期</param>
/// <param name="pathweb">路径</param>
private void InitLog(string sCurDate,string pathweb)
{
if (sCurDate!=""||sCurDate!=null)
{
logpath = pathweb+"\"+ sCurDate + ".log";
}
if (!File.Exists(logpath))
{
swWrite = File.CreateText(logpath);
}
else
{
swWrite = File.AppendText(logpath);
}
}
/// <summary>
/// 日志主方法
/// </summary>
/// <param name="sMess">错误</param>
/// <param name="ex">异常</param>
/// <param name="path1">日志路径</param>
public void LogError(string sMess, Exception ex,string path1)
{
DateTime dt = DateTime.Now;
string sCurDate = dt.ToShortDateString();
if (swWrite == null)
{
InitLog(sCurDate,path1);
}
swWrite.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
swWrite.WriteLine("输出信息:"+sMess);
if (ex != null)
{
swWrite.WriteLine("异常信息:\r\n"+ex.ToString());
swWrite.WriteLine("异常堆栈:\r\n" + ex.StackTrace);
}
swWrite.WriteLine("\r\n");
swWrite.Flush();
swWrite.Dispose();
}
3.调用类.
private string showData(string userid)
{
string name = null;
SqlConnection con = null;
SqlCommand com = null;
SqlDataReader sdr = null;
try
{
string sql = "select user_name from hr_basic where user_account='" + userid + "'";
con = new SqlConnection(constr);
com = new SqlCommand(sql,con);
con.Open();
sdr = com.ExecuteReader();
while (sdr.Read())
{
name = sdr["user_name"].ToString();
}
sdr.Dispose();
}
catch (Exception ex)
{
string path1 = Server.MapPath("logs");
Clogs cl = new Clogs();
cl.LogError("错误信息",ex,path1);
}
finally
{
com.Dispose();
con.Close();
}
return name;
}