c# LogHelper记录本地日志

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 16:23   11   0

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*****************************
* 概要:日志
* 设计者:DuanXuWen
* 设计时间:20180309
* 版本:0.1
* 修改者:
* 修改时间:
* ***************************/

namespace Common
{
public class LogHelper
{
/// <summary>
/// 将异常打印到LOG文件
/// </summary>
/// <param name="ex">异常</param>
/// <param name="logAddress">日志文件地址+文件名+后缀</param>
/// <param name="message">自定义异常信息</param>
public static void WriteLog(Exception ex, string logAddress, bool isSendMail, string message = null)
{
try
{
string filePath = System.IO.Path.GetDirectoryName(logAddress);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
StreamWriter fs = new StreamWriter(logAddress, true);
fs.WriteLine("当前时间:" + DateTime.Now.ToString());
fs.WriteLine("特定内容:" + message);
if (ex != null)
{
fs.WriteLine("异常信息:" + ex.Message);
fs.WriteLine("异常对象:" + ex.Source);
fs.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
fs.WriteLine("触发方法:" + ex.TargetSite);
}
fs.WriteLine();
fs.Close();
fs.Dispose();
if (isSendMail)
{
message = (ex != null) ? message + ex.ToString() : message;
MailHelper.SendMsg(message);
}
}
catch (Exception e)
{
message = (ex != null) ? message + ex.ToString() : message;
MailHelper.SendMsg(e.ToString() + "【详细信息】:" + message);
}
}

/// <summary>
/// 记录系统日志
/// </summary>
/// <param name="fileName"></param>
/// <param name="errorMsg"></param>
public static void RecordLog(string fileName, string errorMsg)
{
try
{
string filePath = Environment.CurrentDirectory + "\\Log\\ErrorMsg\\";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string path = filePath + fileName + ".txt";
if (!File.Exists(path))
{
FileInfo myfile = new FileInfo(path);
FileStream fs = myfile.Create();
fs.Close();
}
StreamWriter sw = File.AppendText(path);
sw.WriteLine(errorMsg);
sw.Flush();
sw.Close();
}
catch (Exception ex)
{
MailHelper.SendMsg(ex.ToString());
}
}
}
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP