printf style logging for f#

假装没事ソ 提交于 2019-12-18 08:55:32

问题


How do i setup a printf-style logger for f# using logging library similar to log4net. i have Log.Debug, Info, Warn, etc. functions that are similar to DebugFormat or InfoFormat in log4net. i tried to setup type extensions for my Log class that i could call in printf style like Log.Debugf "%s" "foo". my generic log function looks like this:

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

i am having trouble with the extension function signature to log to my Debug function... i tried using Debugf format and Debug


回答1:


I'm not familiar with log4net, but assuming you're logging to a MessageBox (like the pros do), you can do the following:

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

In this case, since Show takes a string, it can be shortened to:

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



回答2:


you mean something like this ?

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"



回答3:


You can use standard logging subsystem that defined in System.Diagnostic namespace. You shall be sure that your logging enviromnet correctly initialized. For example something like this (part of example in C#) but it easy is linked with f# code.

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");

so in f#

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

For more convenient you can use another trace listener that definded by third party programmer. For example lool at : AlignedTextWriterTraceListener



来源:https://stackoverflow.com/questions/5277902/printf-style-logging-for-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!