首页 .NET/Web C#记录本地Log日志方法

C#记录本地Log日志方法

作者:胡同里的砖头 围观群众:273 更新于:2023-07-07

方法一:利用Trace进行记录,也很简单

//每次启动新建一个日志文件
string currTime = DateTime.Now.ToString("yyyyMMddHHmmss");
Trace.Listeners.Add(new TextWriterTraceListener("Log"+currTime+".log", "myListener"));


Trace.TraceInformation("XXX"); //记录日志


//退出的时候清空
Trace.Flush();






方法二:单独写一个日志类直接调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Common 的摘要描述
/// </summary>
public class Common
{
public Common()
{


public static void PutLog( string strValue)
{
string strLogFileName;
string strLogDirectory;


try
{


strLogDirectory = System.Web.HttpContext.Current.Server.MapPath("~/") + @"\LOG";

if (!System.IO.Directory.Exists(strLogDirectory))
System.IO.Directory.CreateDirectory(strLogDirectory);

strLogFileName = strLogDirectory + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
strValue = DateTime.Now.ToString("HH:mm:ss") + '\t' +strValue;

if (System.IO.File.Exists(strLogFileName))
{
System.IO.StreamWriter sr = System.IO.File.AppendText(strLogFileName);
sr.WriteLine(strValue);
sr.Close();
}
else
{
System.IO.StreamWriter sr = System.IO.File.CreateText(strLogFileName);
sr.WriteLine(strValue);
sr.Close();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
调用的时候直接用Common.PutLog("查庫存耗時:" + ts.Seconds.ToString());

路径和日志文件命名规则自己定

  • 本文标题: C#记录本地Log日志方法
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8