csharp 错误日志/时间日志

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 错误日志/时间日志相关的知识,希望对你有一定的参考价值。

  //declare global varible of class Stopwatch
  Stopwatch stopWatch;
  
  //start the stopwatch
   stopWatch.Start();
   
   //place time logger in method
  private void LogInvalidLocation(string location, Job item)
  {
     //code here

    TimeLogger(MethodBase.GetCurrentMethod().Name);
  }
  
//timelogger method
 private void TimeLogger(string name)
  {
      stopWatch.Stop();

      string logPath = Path.Combine(basePath, "TimeLog");

      //Console.WriteLine("Writing in timeLog");

      if (!Directory.Exists(logPath))
          Directory.CreateDirectory(logPath);

      string logFile = Path.Combine(logPath, String.Format("TimeLog_{0:yyyy-MM-dd}.txt", DateTime.Now));

      //Console.WriteLine(message);
      using (StreamWriter writer = new StreamWriter(logFile, true))
      {
          writer.WriteLine(string.Format("Method name :{0} , Time taken :{1} milliseconds", name, stopWatch.ElapsedMilliseconds));
      }

      stopWatch = Stopwatch.StartNew();
  }
//log in try...catch
  try
  {
      //code here....
  }
  catch (Exception ex)
  {
      Log(ex.Message);
  }
  
//log method
private void Log(string message)
{
    basePath = @"C:\Users\kaveer\Desktop\XmlFeed\"
    logPath = Path.Combine(basePath, "Log");
    if (!Directory.Exists(logPath))
        Directory.CreateDirectory(logPath);
    string logFile = Path.Combine(logPath, String.Format("Log_{0:yyyy-MM-dd}.txt", DateTime.Now));
    Console.WriteLine(message);
    using (StreamWriter writer = new StreamWriter(logFile, true))
    {
        writer.WriteLine(string.Format("{0:yyyy.MM.dd HH:mm:ss}: {1}", DateTime.Now, message));
    }
}

以上是关于csharp 错误日志/时间日志的主要内容,如果未能解决你的问题,请参考以下文章

csharp dbcontext日志操作

csharp 异常日志

csharp EventLog系统日志的示例

csharp 将事件日志记录添加到UserAudit表

csharp 实体框架核心 - SQL查询控制台日志记录

csharp SOAP日志记录(记录所有传入和传出的xml)