My Technical Notes

Tuesday, 22 July 2014

Writing a simple LogFactory using F# (with NLog)


type LogFactory(path:string) =
    let mutable loggingConfiguration:NLog.Config.LoggingConfiguration = null

    do
        loggingConfiguration <- new NLog.Config.LoggingConfiguration()
        NLog.LogManager.Configuration <- loggingConfiguration
        NLog.LogManager.Configuration.Reload() |> ignore
        
    member this.getLogger (loggerName:string) =
        let targetName = Guid.NewGuid().ToString()
        
        let target = 
            let y = new NLog.Targets.FileTarget()
            y.FileName <- NLog.Layouts.Layout.op_Implicit( Path.Combine(path, loggerName) + ".txt" )
            y

        loggingConfiguration.AddTarget(targetName, target)
        loggingConfiguration.LoggingRules.Add(
            new NLog.Config.LoggingRule(loggerName, NLog.LogLevel.Trace, loggingConfiguration.ConfiguredNamedTargets |> Seq.last )
            )
        NLog.LogManager.Configuration <- loggingConfiguration
        NLog.LogManager.Configuration.Reload() |> ignore
        NLog.LogManager.GetLogger(loggerName)

No comments: