使用 Trace 將日誌輸入到檔案中

2021-09-07 21:29:49 字數 2080 閱讀 1965

工具沒有好壞,只有適不適用。由於專案中用 log4net 過重,所以使用 trace 代替了 log4net 輸入一些簡單的日誌資訊;

自定義監聽檔案

using

system;

using

system.configuration;

using

system.diagnostics;

using

system.io;

namespace

iron.common

}//////

/// private

string

filepath

directpath =directpath.trim();

if (!directory.exists(directpath)) //

判斷資料夾是否存在,如果不存在則建立

return

string.format(@"

\_.log

", directpath, datetime.now.tostring("

yyyy.mm.dd

"), system.diagnostics.process.getcurrentprocess().processname);}}

public

override

void write(string

message)

public

override

void writeline(string

message)

public

override

void traceevent(traceeventcache eventcache, string source, traceeventtype eventtype, int id, string

message)

public

override

void write(object o, string

category)

if (o is exception) //

如果引數o是異常類,輸出異常訊息+堆疊,否則輸出o.tostring()

else

if (o != null

)

writeline(msg);}}

}

測試**

private

static

void main(string

args)

catch

(exception ex)

\r\n

", ex.message, ex.stacktrace);

}return

;}

輸出日誌為:

odas.exe error: 0 : 2017-08-24

00:05:28

attempted to divide by zero.

at ironfo.test.views.demo01.list.controlrefresh(object sender, routedeventargs routedeventargs)

in c:\code\odas\views\demo01\list.xaml.cs:line 43

如果要修改日誌的級別、修改日誌輸出目錄,可修改配置檔案:

<

configuration

>

<

system.diagnostics

>

<

switches

>

<

add

name

="tracelevel"

value

="info"

/>

switches

>

system.diagnostics

>

<

>

>

configuration

>

注意:trace.write() 等日誌輸出方法,不受等級的限制

使用Trace實現程式日誌

在程式開發過程中,有時需要對程式執行狀況做一些日誌記錄,以便以後查詢,維護之用。有時我們可以使用開源日誌元件,如log4net,nlog,entlib log等,但有時為簡便,netframework中trace,debug就可以用來記錄日誌。並且也比較靈活。位於system.diagnostice...

C 使用Trace記錄日誌

c 記錄日誌比較簡單的方法之一是用.net自帶的日誌記錄工具trace類 有多種寫法,比較靈活的一種 如下 每次啟動新建乙個日誌檔案 string currtime datetime.now.tostring yyyymmddhhmmss trace.listeners.add new textwr...

C 使用Trace記錄程式日誌

在程式開發中,我們通常需要記錄程式執行的狀態,在程式部署後,發生的異常可以記錄在日誌中,便於發現程式潛在的問題。在.net平台,有很多優秀的日誌類庫,例如log4net。如果程式很小,我們可以自己通過c 的trace類來實現乙個基本的日誌記錄功能。下面直接看 public class tracehe...