SimplePSLogger.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846

class SimplePSLogger : System.IDisposable {
    
    # Create with providers
    SimplePSLogger([string]$Name, [LoggingProvider[]]$LoggingProviders) {
        $this.Name = $Name
        $this.AddLoggingProviders($LoggingProviders)
        Write-Information "Logging providers registered - $($this.LoggingProviders.Count)" -InformationAction Continue
        Write-Information "$([Environment]::NewLine)----------------- SimpleLogger instance initialized with name '$Name' ---------------------- $([Environment]::NewLine)" -InformationAction Continue
    }

    <#------------------------------- Members Variables ----------------------------------#>
    hidden [string] $Name = $null
    hidden [System.Collections.ArrayList] $LoggingProviders = [System.Collections.ArrayList]@()
    hidden [string] $DefaultLogLevel = "information"
    hidden [hashtable] $LogLevels = [ordered]@{"verbose" = 0; "debug" = 1; "information" = 2; "warning" = 3; "error" = 4; "critical" = 5; "none" = 6 }
    <#------------------------------- Members Variables ----------------------------------#>
    
    hidden static [object] CreateLogger($Name, [LoggingProvider[]]$LoggingProviders) {
        if (-Not $Name) {
            throw "Cannot create logger without 'name'"
        }
        return [SimplePSLogger]::new($Name, $LoggingProviders)
    }

    hidden static [string] GenerateLoggerName() {
        # https://devblogs.microsoft.com/scripting/powertip-create-a-new-guid-by-using-powershell/
        return [Guid]::NewGuid().ToString()
    }

    hidden [string] GetTimestamp() {
        return (Get-Date).ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss:ffff tt")
    }

    hidden [string] GetLogLevel($level) {
        # TODO : optimize it later
        if (-Not $this.LogLevels[$level]) {
            Write-Information "Log level '$level' not supported, defaulting to '$($this.DefaultLogLevel)'" -InformationAction Continue
            $level = $this.DefaultLogLevel
        }
        return $level
    }

    <# This method checks configured loglevel(for provider) against
        user provided loglevel in .Log() method
    #>

    hidden [Boolean] ShouldLog($ConfugeredLevel, $Level) {
        # provided level should be greater or equal to configured value.
        return $this.LogLevels[$ConfugeredLevel] -le $this.LogLevels[$Level]
    }

    hidden [void] AddLoggingProviders([LoggingProvider[]]$loggers) {
        foreach ($logger in $loggers) {
            if ($logger.GetType() -ne [LoggingProvider]) {
                throw [InvalidCastException]::new()
            }
            $this.LoggingProviders.Add($logger)
        }
    }

    # TODO : need more information.
    [void] Dispose() {
        Write-Warning "$($this.Name) SimplePSLogger disposed" -WarningAction Continue
    }

    <#------------------------------- /Internals ---------------------------------------#>

    
    <#------------------------------- Public methods ---------------------------------------#>
    [void] Log(
        [string]$Level, 
        [object]$Message
    ) {
        if (-Not $Level) {
            $Level = $this.DefaultLogLevel
        }
        $Level = $this.GetLogLevel($Level)

        if (-Not $($Message.GetType() -eq 'String')) {
            $Message = $Message | ConvertTo-Json -Compress -Depth 100 
        }

        if ($this.LoggingProviders.Count -le 0) {
            Write-Information "Zero logging providers registered." -InformationAction Continue
        }

        foreach ($logger in $this.LoggingProviders) {
            Write-Verbose "Writing using logger - $($logger.Name)"
            if (-Not $logger.Config) {
                try {
                    if ($this.ShouldLog($this.DefaultLogLevel, $Level) -and $logger.Config["Enabled"]) {
                        Invoke-Command $logger.Function -ArgumentList $this.Name, $Level, $Message -ErrorAction Continue   
                    }
                }
                catch {
                    Write-Warning "---------------------- Attention : error occurred while writing log------------------" -WarningAction Continue
                    Write-Warning "$_" -WarningAction Continue
                    Write-Warning "---------------------- /Attention ------------------" -WarningAction Continue
                }
                finally {
                    # TODo : need help
                }
            }
            else {
                try {
                    $UserProvidedLogLevel = if (-Not $logger.Config["LogLevel"]) { $this.DefaultLogLevel }else { $logger.Config["LogLevel"] }
                    if ($this.ShouldLog($UserProvidedLogLevel, $Level) -and $logger.Config["Enabled"]) {
                        Invoke-Command $logger.Function -ArgumentList ($this.Name), $Level, $Message, ($logger.Config) -ErrorAction Continue
                    }
                }
                catch {
                    Write-Warning "---------------------- Attention : error occurred while writing log------------------" -WarningAction Continue
                    Write-Warning "$_" -WarningAction Continue
                    Write-Warning "---------------------- /Attention ------------------" -WarningAction Continue
                }
                finally {
                    #TODO : need help
                }
            }
        }
    }


    [void] Log(
        [object]$Message
    ) {
        # Default loglevel
        $Level = $this.DefaultLogLevel
        $this.Log($Level, $Message)
    }

    <#
        .SYNOPSIS
        Register your custom logging provider
        .DESCRIPTION
            Use this method of [SimplePSLogger] to register your custom logging provider.
            Make sure that your custom logging script/module/function is available before registering.
             
        .PARAMETER Name
            Name of your logging provider
        .PARAMETER ProviderFunctionName
            Powershell function name of your provider
 
        .PARAMETER Configuration
            Configuratoin object needed for your logging provider
            Example configuration object :
            $config = @{
                Enabled = $true
                LogLevel = "information"
                Authkey = "key"
            }
         
        .EXAMPLE
            $myLogger = New-SimplePSLogger -Name "mylogger"
            $myLogger.RegisterProvider("myAwesomeProvider", "New-MyAwesomeProvider-Logger", $config)
        .NOTES
            Make sure that "New-MyAwesomeProvider-Logger" function and it's dependencies are imported/initialized before registering your provider
    #>

    [void] RegisterProvider($Name, $ProviderFunctionName, $Configuration) {
        try {
            Write-Information "$([Environment]::NewLine)----------------- SimpleLogger - Registering Custom Provider ---------------------- $([Environment]::NewLine)" -InformationAction Continue 
            if (-Not $Name) {
                throw "Provider name is required"
            }
            if (-Not $ProviderFunctionName) {
                throw "Provider function name is required"
            }
            Get-Command -Name $ProviderFunctionName -ErrorAction Stop
            $ProviderFunctionCode = [scriptblock]::Create($(Get-Command -Name $ProviderFunctionName).Definition)
            $ProviderLogger = [LoggingProvider]::Create($Name, $ProviderFunctionCode, $Configuration)
            $this.AddLoggingProviders($ProviderLogger)
            Write-Information "$([Environment]::NewLine)----------------- SimpleLogger - Registering Custom Provider ---------------------- $([Environment]::NewLine)" -InformationAction Continue
        }
        catch [System.Management.Automation.CommandNotFoundException] {
            throw "Provider module/function is recognized as name of cmdlet, please make sure that your provider is available"
        }
        catch {
            throw $_.Exception.Message
        }
    } 

    <#
        Processes remaining logs
    #>

    [void] Flush() {
        foreach ($logger in $this.LoggingProviders) {
            if ($logger.Config -and $logger.Config["Flush"]) {
                "Clearing $($logger.Name)'s buffered logs"
                Write-Information "Clearing $($logger.Name)'s buffered logs" -InformationAction Continue
                try {
                    Invoke-Command $logger.Function -ArgumentList ($this.Name), "information", "flush logs", $logger.Config, $true -ErrorAction Continue
                }
                catch {
                    Write-Warning "---------------------- Attention : error occurred while flushing logs of $($logger.Name) ------------------" -WarningAction Continue
                    Write-Warning "$_" -WarningAction Continue
                    Write-Warning "---------------------- /Attention ------------------" -WarningAction Continue
                }
                finally {
                    #TODO : need help
                }
            }
            
        }
    }
    <#------------------------------- /Public methods : everything is public tho :P ---------------------------------------#>
}


class LoggingProvider {

    hidden LoggingProvider($name, $function, $config) {
        Write-Information "Registering '$name' provider" -InformationAction Continue
        if (-Not $name) {
            throw "Logging provider name is required"
        }
        if (-Not $function) {
            throw "Logging provider function is required"
        }
        #TODO : validate function type
        if ($($function.GetType()) -ne [scriptblock]) {
            throw "Logging provider's function should be ScriptBlock"
        }
        if (-Not $config) {
            Write-Information "Configurations not provided for '$name' provider or it does not need any configurations." -InformationAction Continue
        }
        $this.Config = $config
        $this.Name = $name
        $this.Function = $function
        Write-Information "Registered '$name' provider" -InformationAction Continue
    }

    hidden static [LoggingProvider] Create($name, $function, $config) {
        return [LoggingProvider]::new($name, $function, $config)
    }

    [string] $Name
    [object] $Function
    [object] $Config
}

<#
.SYNOPSIS
   Create new SimplePSLogger instance
.DESCRIPTION
    You can create multiple loggers for one action but we recommend creating one single logger for your action
    SimplePSLogger logger automatically registers x loggers.
    Custom logging provider support will be added soon.
     
.PARAMETER Name
    SimplePSLogger name which is used to identify current logger instnace
    Examples : your script name, unique task name etc.
    It will help you to analyze logs
 
.PARAMETER Configuration
    SimplePSLogger configuratoin object, this will contain configurations for supported/reistred providers
    Configuration for each provider should be defined by creating new section/key with it's name
 
    Example configuration object :
    $SimplePSLoggerConfig = @{
    Name = "config-example"
    Providers = @{
        File = @{
            LiteralFilePath = "G:\Git\simple-ps-logger\Examples\example-with-config-file\example-with-config.log"
        }
        }
    }
.EXAMPLE
    New-SimplePSLogger -Name "action-1234"
.EXAMPLE
    New-SimplePSLogger -Configuration $SimplePSLoggerConfig
.FUNCTIONALITY
    new, new logger, create logger, create
.NOTES
 
#>

function New-SimplePSLogger {
    param (
        [Parameter(Mandatory = $false, HelpMessage = "Unique/Identifiable name for your logger instance")]
        [string]
        $Name,
        [Parameter(Mandatory = $false, HelpMessage = "Config object")]
        [object]
        <#TODO : Add support to read form file path,
            First class support for object seems resonable because user can add secrets by without storing those in config file
        #>

        $Configuration,
        # Set Default
        [Parameter(Mandatory = $false)]
        [switch]
        $SetDefault
    )

    try {
        if (-Not $Name) {
            if ($null -ne $Configuration) {
                if (-Not $Configuration["Name"]) {
                    Write-Information "SimplePSLogger name not provided, initializing instance with auto generated name : '$Name'" -InformationAction Continue
                    $Name = [SimplePSLogger]::GenerateLoggerName()
                }
                $Name = $Configuration["Name"]
            }
            else {
                $Name = [guid]::NewGuid()
            }
        }

        Write-Information "----------------- Initializing SimpleLogger instance with name '$Name' ----------------------`n" -InformationAction Continue

        <# NOTE : We can merge User provided with default configurations but
            merging deep hastables is complicated and expensive.
        #>

        if (-Not $Configuration) {
            #TODO : Create and read default config file.
            Write-Warning "Configuration not provided, all providers will get configured without configurations(Not recommended)" -WarningAction Continue
            $Configuration = @{
                Providers = @{
                    Console = @{
                        Enabled  = $true
                        LogLevel = "information"
                    }
                }
            }
        }
        else {
            # TODO : will it be helpful if we enable Console provider forcefully?
            if ($Configuration.Providers["Console"]) {
                $Configuration.Providers.Console["Enabled"] = $true
            }
            else {
                $Configuration.Providers["Console"] = @{
                    Enabled = $true
                }
            }
        }
        $NestedProviders = $((Get-Module SimplePSLogger).NestedModules)
        if ($NestedProviders.Count -le 0) {
            Write-Error "Zero logging provider registred, there is no use of SimplePSLogger with logging providers." -ErrorAction Continue
        }
        $Loggers = [System.Collections.ArrayList]@()
        foreach ($provider in $NestedProviders) {
            $ProviderSectionName = $($provider.Name -replace "SimplePSLogger.", "")
            $ProviderSectionConfig = $Configuration.Providers[$ProviderSectionName]

            # IsEnabled?
            if ($ProviderSectionConfig -and $ProviderSectionConfig["Enabled"]) {
                $ProviderFunctionName = "New-$ProviderSectionName-Logger"
                if (-Not $($provider.ExportedCommands.Keys.Contains($ProviderFunctionName))) {
                    Write-Information "$($provider.Name) does not have module member exposed in 'New-YuorLoogerName-Logger' format" -InformationAction Continue
                }
                else {
                    $ProviderFunctionCode = [scriptblock]::Create($(Get-Command $ProviderFunctionName).Definition)
                    $ProviderLogger = [LoggingProvider]::Create($ProviderSectionName, $ProviderFunctionCode, $ProviderSectionConfig)
                    # .Add method retuns int32 in pipeline
                    $null = $Loggers.Add($ProviderLogger)
                }
            }            
        }
        $logger = [SimplePSLogger]::CreateLogger($Name, $Loggers)
        Set-SimplePSLoggerContext -Logger $logger -Default:$SetDefault -ErrorAction Continue
    }
    catch {
        throw
    }
}

<#
.SYNOPSIS
    It sets SimplePSLogger Context
.DESCRIPTION
    SimplePSLogger context contains all instances intialized by the user along with the DEFAULT_LOGGER
.EXAMPLE
.NOTES
    Used internally
#>

Function Set-SimplePSLoggerContext {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [SimplePSLogger]
        $Logger,
        [Parameter(Mandatory = $false)]
        [switch]
        $Default
    )

    if (-Not $script:SimplePSLoggerContext -or $script:SimplePSLoggerContext.Count -le 0) {
        $script:SimplePSLoggerContext = @{
            DEFAULT_LOGGER = $null
            Instances      = @{}
        }
    }
    if (-Not $script:SimplePSLoggerContext.DEFAULT_LOGGER) {
        Add-SimplePSLogger $Logger -SetDefault -Force
    }
    if ($Default) {
        Add-SimplePSLogger $Logger -SetDefault
    }
    else {
        <# NOTE : If user creates new logger with exiting name then
            the -Force parameter replaces existing logger with the new logger instance
         #>

        Add-SimplePSLogger $Logger -Force
    }
}

<#
.SYNOPSIS
    Add logger instance to SimplePSLogger context
.DESCRIPTION
    Add logger instance to SimplePSLogger context
 
.PARAMETER Logger
    SimplePSLogger instance
.PARAMETER SetDefault
    Sets default logger if provided
.PARAMETER Force
    If logger instance with the same name is already exists it flag replaces it.
.NOTES
    Used internally
#>

function Add-SimplePSLogger {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [SimplePSLogger]
        $Logger,
        [Parameter(Mandatory = $false)]
        [switch]
        $SetDefault,
        [Parameter(Mandatory = $false)]
        [switch]
        $Force
    )
    if ($Force) {
        $script:SimplePSLoggerContext.Instances.Remove($Logger.Name)
        $script:SimplePSLoggerContext.Instances.Add($Logger.Name, $Logger)
    }
    else {
        if ($null -ne $(Get-SimplePSLogger -Name $Logger.Name)) {
            Write-Error "Logger witn name $($Logger.Name) already exists. You cannot create logger with same name." -ErrorAction Continue
        }
        $script:SimplePSLoggerContext.Instances.Add($Logger.Name, $Logger)
    }

    if ($SetDefault) {
        $script:SimplePSLoggerContext.DEFAULT_LOGGER = $Logger
    }
}

<#
.SYNOPSIS
    Retrieve registred logger instance by name or list all of them
.DESCRIPTION
    Retrieve registred logger instance by name or list all of them
.EXAMPLE
    Get-SimplePSLogger -All
.INPUTS
 
.OUTPUTS
    Returns Object[] of all logger instances
.EXAMPLE
    Get-SimplePSLogger -Name "my-logger"
.INPUTS
     
.OUTPUTS
    Returns [SimplePSLogger]
.NOTES
     
#>

function Get-SimplePSLogger {
    [CmdletBinding()]
    param (
        # Name of the logger instance .PARAMETER
        [Parameter(Mandatory = $false)]
        [string]
        $Name,
        # List all logger instances .PARAMETER
        [Parameter(Mandatory = $false)]
        [switch]
        $List
    )
    
    if ($List) {
        return $script:SimplePSLoggerContext.Instances.Values
    }
    if (-Not $script:SimplePSLoggerContext -or $null -eq $script:SimplePSLoggerContext) {
        return $null
    }
    else {
        return $script:SimplePSLoggerContext.Instances[$Name]
    }
}

<#
.SYNOPSIS
    Set DEFAULT LOGGER
.DESCRIPTION
    If you have mutiple logger instances, you can set default logger of your choice before logging messages.
.EXAMPLE
    Set-SimplePSLogger -Name "my-logger"
.INPUTS
     
.OUTPUTS
     
.NOTES
    You can use one(DEFAULT LOGGER) at a time.
#>

function Set-SimplePSLogger {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName)]
        [string]
        $Name
    )
    Process {
        if (-Not $script:SimplePSLoggerContext.Instances[$Name]) {
            throw "Logger instance not found with name $Name"
        }
        $script:SimplePSLoggerContext.DEFAULT_LOGGER = $script:SimplePSLoggerContext.Instances[$Name]
        Write-Verbose "Set default logger as $($script:SimplePSLoggerContext.DEFAULT_LOGGER.Name)"
    }
}

<#
.SYNOPSIS
    Remove or close existing logger instance
.DESCRIPTION
    You need to remove logger before exiting from your script.
    This removes logger so that you can register and use new logger in the same session.
.EXAMPLE
    Remove-SimplePSLogger -All
    Remove-SimplePSLogger -Name "my-logger"
.INPUTS
     
.OUTPUTS
     
.NOTES
    ! It is recommended to remove all loggers before exiting from your script.
#>

function Remove-SimplePSLogger {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        [Parameter(Mandatory = $false)]
        [switch]
        $All
    )
    process {
        if ($All) {
            $script:SimplePSLoggerContext = @{}
            return
        }
        else {
            if ($null -ne $(Get-SimplePSLogger -Name $Name)) {
                Write-Information "Removing Logger $Name" -InformationAction Continue
                $script:SimplePSLoggerContext.Instances.Remove($Name)
                if ($script:SimplePSLoggerContext.DEFAULT_LOGGER.Name -eq $Name) {
                    $script:SimplePSLoggerContext.DEFAULT_LOGGER = $null    
                }
            }
        }
    }
}

<#
.SYNOPSIS
    Write log messages
.DESCRIPTION
    Write log messages
.EXAMPLE
    Write-Log "info message"
    Write-Log "warn messahe" "warning"
    Write-Log "error message" "error"
.INPUTS
     
.OUTPUTS
     
.NOTES
    ! Default log level is 'information'
#>

function Write-SimpleLog {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Log message", ValueFromPipelineByPropertyName)]
        [object]
        $Message,
        [Parameter(Mandatory = $false, HelpMessage = "LogLevel", ValueFromPipelineByPropertyName)]
        [ValidateSet("verbose", "debug", "information", "warning", "error", "critical")]
        [string]
        $Level
    )
    process {
        if (-Not $script:SimplePSLoggerContext.DEFAULT_LOGGER) {
            Write-Warning "Default Logger not found, using latest available logger"
            $loggers = Get-SimplePSLogger -All
            if ($loggers.Count -gt 0) {
                $NextDefaultLogger = $loggers.Keys[0]
                $script:SimplePSLoggerContext.DEFAULT_LOGGER = $script:SimplePSLoggerContext.Instances[$NextDefaultLogger]
            }
            else {
                Write-Error "Loggers not available. You might have removed logger, Please create new logger using New-SimplePSLogger cmdlt." -ErrorAction Continue
                return
            }
        }
        $Logger = $script:SimplePSLoggerContext.DEFAULT_LOGGER
        $Logger.Log($Level, $Message)
    }
}

<#
.SYNOPSIS
    Flush buffered logs
.DESCRIPTION
    It's always better to batch your tasks and execute them as one task, it improves performance.
    To avoid missing logs. flush them before exiting your script or flow.
.EXAMPLE
    Clear-Buffer # This flushes buffered logs of DEFAULT LOGGER
    Clear-Buffer -Name "my-looger" # This flushes logs of provided logger instance
    Clear-Buffer -All # This flushes all buffered logs of all logger instances
.INPUTS
     
.OUTPUTS
     
.NOTES
    Always clear call this command at the end of your script, usually in finally block
#>

function Clear-Buffer {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, HelpMessage = "Logger name", ValueFromPipelineByPropertyName)]
        [string]
        $Name,
        [Parameter(Mandatory = $false)]
        [switch]
        $All
    )
    Process {
        if (-Not $Name -and -Not $All) {
            $logger = $script:SimplePSLoggerContext.DEFAULT_LOGGER
            if ($logger) {
                $logger.Flush()
            }
            return
        }

        if ($All) {
            foreach ($logger In $script:SimplePSLoggerContext.Instances.Values) {
                if ($logger) {
                    $logger.Flush()
                }
            }
            return
        }
        if ($Name) {
            $logger = Get-SimplePSLogger -Name $Name
            if (-Not $logger) {
                $logger.Flush()
            }
            return
        }
    }
}

<#
.SYNOPSIS
    Register your custom logging provider. Read more here https://spsl.geekwhocodes.me/docs/custom-provider-registration
.DESCRIPTION
    Register your custom logging provider. Read more here https://spsl.geekwhocodes.me/docs/custom-provider-registration
.EXAMPLE
    Register-LoggingProvider -Name "AwesomeLogger" -FunctionName "FunctionName" -Configuration @{
            Enabled = $true
            LogLevel = "information"
            Authkey = "key"
        }
.INPUTS
     
.OUTPUTS
     
.NOTES
    Make sure Function/Module is imported before registering your provider
#>

function Register-LoggingProvider {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Name for your custom logging provider name")]
        [ValidateNotNull()]
        [string]
        $Name, 
        [Parameter(Mandatory = $true, HelpMessage = "Function name which implements SimplePSLogger custom provider interface.")]
        [ValidateNotNull()]
        [string]
        $FunctionName,
        [Parameter(Mandatory = $true, HelpMessage = "Configurations required for your logging provider")]
        [ValidateNotNull()]
        [object]
        $Configuration
    )

    if (-Not $script:SimplePSLoggerContext) {
        Write-Error "SmplePSLogger is not created. Create logger using New-SimplePSLogger before registering custom provider" -ErrorAction Continue
        return
    }
    if (-Not $script:SimplePSLoggerContext.DEFAULT_LOGGER) {
        Write-Error "DEFAULT LOGGER is not set, Please set default logger using Set-SimplePSLogger cmdlt" -ErrorAction Continue
        return 
    }
    $script:SimplePSLoggerContext.DEFAULT_LOGGER.RegisterProvider($Name, $FunctionName, $Configuration)
}

Export-ModuleMember -Function New-SimplePSLogger, Get-SimplePSLogger, Set-SimplePSLogger, Remove-SimplePSLogger, Register-LoggingProvider, Write-SimpleLog , Clear-Buffer
# SIG # Begin signature block
# MIIYYQYJKoZIhvcNAQcCoIIYUjCCGE4CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU7/rGrfGR3sJjiyHi5iCAe32K
# wV+gghKzMIIFcDCCA1igAwIBAgIQZDtcNubuNpVEfXOVHbciTzANBgkqhkiG9w0B
# AQsFADBQMSUwIwYDVQQDDBxHYW5lc2ggUmFza2FyIFNpbXBsZVBTTG9nZ2VyMScw
# JQYJKoZIhvcNAQkBFhhnYW5lc2hyYXNrYXJAb3V0bG9vay5jb20wHhcNMjAwNzA0
# MTgzMjE0WhcNMjEwNzA0MTg1MjE0WjBQMSUwIwYDVQQDDBxHYW5lc2ggUmFza2Fy
# IFNpbXBsZVBTTG9nZ2VyMScwJQYJKoZIhvcNAQkBFhhnYW5lc2hyYXNrYXJAb3V0
# bG9vay5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCywhH9ot8P
# 9i7rClMbjRwIH1DeVotpNCscFvcSqEbMo3AtJ0WFOb13Xt/g1d0axBa3DvriedVR
# KF2AD0U8jGIsToPBnIdBKVXQ72CN+i1BHrqu9DOI7+csE0hVFAqYCv7qIXgAGued
# FQOe1oD5q3H3GlzLDfwhk/cdLCt+WEgzWdtTca8kirNo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