using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogHelper
{
public static class LogHelper
{
//拼接日志目录
static string appLogPath = AppDomain.CurrentDomain.BaseDirectory +
"log/";
/// <summary>
/// 写入日志
/// </summary>
/// <param name="ex">异常对象</param>
public static void WriteLog(Exception ex)
{
//日志目录是否存在 不存在创建
if (!
Directory.Exists(appLogPath))
{
Directory.CreateDirectory(appLogPath);
}
StringBuilder logInfo =
new StringBuilder(
"");
string currentTime = System.DateTime.Now.ToString(
"[yyyy-MM-dd HH:mm:ss]");
if (ex !=
null)
{
logInfo.Append("\n");
logInfo.Append(currentTime +
"\n");
//获取描述当前的异常的信息
logInfo.Append(ex.Message +
"\n");
//获取当前实例的运行时类型
logInfo.Append(ex.GetType() +
"\n");
//获取或设置导致错误的应用程序或对象的名称
logInfo.Append(ex.Source +
"\n");
//获取引发当前异常的方法
logInfo.Append(ex.TargetSite +
"\n");
//获取调用堆栈上直接桢的字符串表示形式
logInfo.Append( ex.StackTrace +
"\n");
}
System.IO.File.AppendAllText(appLogPath + DateTime.Now.ToString(
"yyyy-MM-dd") +
".log", logInfo.ToString());
}
}
}
调用方法:
try
{
while (
true)
{
int a =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine("您输入的是:" +
a);
}
}
catch (Exception ex)
{
LogHelper.WriteLog(ex);
}
Console.Write("OVER");
Console.Read();
}
转载于:https://www.cnblogs.com/siyunianhua/p/6950835.html
相关资源:C#常用工具类代码集合Util(自己工作总结)