printf style logging for f#

后端 未结 3 467
滥情空心
滥情空心 2020-12-21 08:41

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 InfoFo

相关标签:
3条回答
  • 2020-12-21 08:50

    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

    0 讨论(0)
  • 2020-12-21 08:53

    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
    
    0 讨论(0)
  • 2020-12-21 09:06

    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"
    
    0 讨论(0)
提交回复
热议问题