应用程序中的日志文件使用C# [英] Log File in an application made it in C#

查看:85
本文介绍了应用程序中的日志文件使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,如何创建日志文件以记录我的应用程序中的所有活动?

Hello, how can I make a log file to record all the activities from my aplication?

推荐答案

您可以自定义实现,将所有信息转储到文本文件或者像Log4Net一样使用Logging Frameworks。



查看 log4net教程 [ ^ ]
You can custom implement , dump all the info to Text file or use Logging Frameworks like Log4Net.

Have a look into log4net Tutorial[^]


几乎在所有情况下,使用类 System.Diagnostics.EventLog

http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx [ ^ ] 。



请参阅我过去关于日志定制的答案。这并不像看起来那么简单:

如何在文件夹下创建事件日志 [ ^ ],

MsBuild OutPut到Windows应用程序中的TextBox [ ^ ]。



关于使用第三方(Apache)开源log4net(请参阅解决方案1),它也很有用。请参阅:

http://en.wikipedia.org/wiki/Log4net#Ports [ ^ ],

http://logging.apache.org/log4net/ [ ^ ]。



在大多数情况下,没有必要使用任何第三方或自烤方法或框架。



-SA
In nearly all cases, use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Please see also my past answer on log customization. This is not as trivial as it may seem:
How to create event log under a folder[^],
MsBuild OutPut to the TextBox on the fly in Windows Application[^].

As to the use of 3rd-party (Apache) open-source log4net (please see Solution 1), it also can be useful. Please see:
http://en.wikipedia.org/wiki/Log4net#Ports[^],
http://logging.apache.org/log4net/[^].

In most cases, there is no a need to use any 3rd-party or self-baked methods or frameworks.

—SA


public static class Logger

{

public static void Log(

string message)

{

File.AppendAllText(

C:\\MyLogFile.txt,

DateTime.Now。

ToShortDateString() ++

DateTime.Now。

ToShortTimeString()+:\ t

+ message + Environment。

NewLine);

}

}



static void Main(string []

args)

{

应用程序。

ThreadException + = new

System.Threading。

ThreadExceptionEventHandler(

Application_ThreadException

); //必须在之前

Application.Run

...

Application.Run();

}

static void Application_

ThreadException(对象

发件人,System.Threading。

ThreadExceptionEventArgs e)

{

Logger.Log(e.Exception。

ToString());

}
public static class Logger
{
public static void Log(
string message)
{
File.AppendAllText(
"C:\\MyLogFile.txt" ,
DateTime.Now.
ToShortDateString() + " " +
DateTime.Now.
ToShortTimeString() + ":\t"
+ message + Environment.
NewLine);
}
}

static void Main( string[]
args)
{
Application.
ThreadException += new
System.Threading.
ThreadExceptionEventHandler(
Application_ThreadException
); //it must be before
Application.Run

Application.Run();
}
static void Application_
ThreadException( object
sender, System.Threading.
ThreadExceptionEventArgs e)
{
Logger.Log(e.Exception.
ToString());
}


这篇关于应用程序中的日志文件使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆