2011-03-11 46 views
2

如何设置登录使用F#的一个printf风格的记录库类似,log4net的。 我有Log.Debug,信息,警告等类似于DebugFormat或InfoFormat在log4net的功能。我试图安装类型扩展我的日志类,我可以在printf类型调用诸如Log.Debugf“%s的”“富”。我一般的日志功能看起来是这样的:printf类型的日志记录F#

let log format = Printf.kprintf (sprintf "%s") format 

我有扩展函数签名的麻烦登录到我的调试功能... 我尝试使用Debugf格式和调试

回答

6

我不熟悉与log4net的,但假设你登录到一个MessageBox(如专业人士做),你可以做到以下几点:

let log format = Printf.kprintf (fun msg -> System.Windows.Forms.MessageBox.Show(msg)) format 

在这种情况下,由于Show需要一个字符串,它可以缩短为:

let log format = Printf.kprintf System.Windows.Forms.MessageBox.Show format 
+0

非常感谢你们俩,我为此跳了一阵子,终于放弃了(一反常态* :)) – Alex 2011-03-11 20:59:32

4

你的意思是这样的?

open System 

type SomeLogger() = 
    member this.Error(format : string, [<ParamArray>]args : obj[]) =() 
    member this.Info(format : string, [<ParamArray>]args : obj[]) =() 


module Extensions = 
    type SomeLogger with 
     member this.FInfo format = Printf.ksprintf (this.Info) format 
     member this.FError format = Printf.ksprintf (this.Error) format 

open Extensions 

let l = new SomeLogger() 
l.FInfo "%d%s" 10 "123" 
2

您可以使用System.Diagnostic命名空间中定义的标准日志记录子系统。 您应确保您的记录环境正确初始化。比如像这样的东西(在C#中的例子的一部分),但它很容易与f#代码链接。

Trace.Listeners.Clear(); 
try { 
    TextWriterTraceListener infoTextLogger = new AlignedTextWriterTraceListener(@"c:\temp\log.log"); 
    infoTextLogger.Filter = new EventTypeFilter(SourceLevels.All); 
    infoTextLogger.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId; 
    Trace.Listeners.Add(infoTextLogger); 
    TextWriterTraceListener consoleWriter = new AlignedTextWriterTraceListener(System.Console.Out); 
    consoleWriter.Filter = new EventTypeFilter(SourceLevels.Information); 
    Trace.Listeners.Add(consoleWriter); 
} catch (Exception exp) { 
    throw exp; 
} 
AlignedTextWriterTraceListener.TraceSourceNameLength = SOURCE_NAME_FIELD_LENGTH; 
Trace.AutoFlush = true; 
Trace.TraceInformation("Logging subsystem has been initiated"); 

所以在F#

open System 
open System.Diagnostics 
module ClientConsole = 
    let Run _ = 
     Trace.TraceInformation("Client started"); 

为了更方便您可以使用由第三方程序员definded另一个跟踪侦听器。 例如lool在:AlignedTextWriterTraceListener