zoukankan
html css js c++ java
自己写的一个日志记录类
using
System;
using
System.IO;
using
System.Net;
namespace
Utils
{
public
class
LogWritter
{
//
禁止创建同时存在多个对象
private
LogWritter()
{}
private
static
LogWritter m_logger
=
null
;
public
static
LogWritter CreateInstance()
{
if
(m_logger
==
null
)
{
m_logger
=
new
LogWritter();
}
return
m_logger;
}
//
设置保存文件位置
private
string
m_filePath
=
string
.Empty;
public
void
SetFilePath(
string
fileName)
{
if
(
!
m_filePath.Equals(fileName))
{
m_filePath
=
fileName;
}
}
/**/
///
<summary>
///
写日志,时间,机器名,日志内容
///
</summary>
///
<param name="content"></param>
public
void
WriteLog(
string
content)
{
string
hostName
=
Dns.GetHostName();
if
(
!
File.Exists(m_filePath))
{
FileStream fStream
=
new
FileStream(m_filePath, FileMode.CreateNew);
fStream.Flush();
fStream.Close();
fStream
=
null
;
}
StreamWriter sWriter
=
new
StreamWriter(m_filePath,
true
, System.Text.Encoding.Default);
string
txtTime
=
"
\n
"
+
"
时间 :
"
+
DateTime.Now.ToString();
string
txtHost
=
"
\n
"
+
"
机器名 :
"
+
hostName;
string
txtError
=
"
\n
"
+
"
错误信息 :
"
+
content;
string
textWrite
=
txtTime
+
txtHost
+
txtError;
sWriter.WriteLine(textWrite);
sWriter.Flush();
sWriter.Close();
sWriter
=
null
;
}
}
}
使用的时候呢,在需要记录的类里面新建一个全局变量,然后初始化,然后设置文件位置.之后就可以记录日志了.
例如:
class
Test
{
private
Utils.LogWritter m_logger
=
null
;
public
Test()
{
m_logger
=
Utils.LogWritter.CreateInstance();
m_logger.SetFilePath(
@"
C:\TestLog.txt
"
);
}
static
void
Main()
{
try
{
string str = "a";
str
.Substring(0, 2);
}
catch
(Exception ee)
{
m_logger.WriteLog(ee.ToString());
}
}
}
今天在csdn上面看到有人找记录错误日志的类,可以记录机器名,时间..
正好有空,就胡乱写了一个.但是有一点还是不太清楚,日志类的记录方法到底静态的好呢?还是普通的好呢?欢迎朋友多提宝贵意见和看法.
查看全文
相关阅读:
CF1119H
oracle 第06章 数据字典
oracle col命令
oracle 第05章 SQL语句
oracle 第04章 字符集
oracle 第03章 体系结构
oracle 第02章 基本操作
oracle 第01章 安装
oracle启动、关闭、重启脚本
第十一周-学习进度条
原文地址:https://www.cnblogs.com/snowlove67/p/273040.html
最新文章
HDU
2020牛客暑期多校训练营(第九场) E Groundhog Chasing Death 数论,思维
【Python学习】获取计算机hostname,ip,mac
【Python学习】psutil获取进行资源
【Python学习】将目录的最高权限给每一个用户
【CSS总结】CSS选择器
【自动化学习】开启chrome静默模式
【Windows学习】BAT远程登录桌面
【Windows学习】CMD执行多条命令
【HTTP学习】Http协议中Cookie详细介绍
热门文章
【工具学习】everything开放http or ftp服务
杂题
Comet OJ
Comet OJ
画家小P
CF1152F
P6060 [加油武汉]传染病研究
CF1060F
CF1151F
CF1119F
Copyright © 2011-2022 走看看