GithubHelp home page GithubHelp logo

poshlog / poshlog Goto Github PK

View Code? Open in Web Editor NEW
189.0 10.0 18.0 638 KB

:nut_and_bolt: PoShLog is PowerShell cross-platform logging module. It allows you to log structured event data into console, file and much more places easily. It's built upon great C# logging library Serilog - https://serilog.net/

License: MIT License

PowerShell 78.69% C# 21.31%
powershell-module powershell module log logging error-reporting error-log serilog serilog-sink serilog-extension

poshlog's Introduction

icon

PoShLog

psgallery psgallery Discord Build Status Support

Serilog for powershell

PoShLog is powershell cross-platform logging module. PoShLog allows you to log structured event data into console, file and much more places easily. It's built upon great C# logging library Serilog.

Key Features

  • Structured log event data
  • Clean and easy to use API
  • Cross-platform
  • Easily extensible

Getting started

If you are familiar with PowerShell, skip to Installation section. For more detailed installation instructions check out Getting started wiki.

Installation

To install PoShLog, run following snippet from powershell:

Install-Module PoShLog

Usage

Setup logger using pipeline fluent API and write some log messages(in this case into file and console):

Import-Module PoShLog

# Create new logger
# This is where you customize, when and how to log
New-Logger |
    Set-MinimumLevel -Value Verbose | # You can change this value later to filter log messages
    # Here you can add as many sinks as you want - see https://github.com/PoShLog/PoShLog/wiki/Sinks for all available sinks
    Add-SinkConsole |   # Tell logger to write log messages to console
    Add-SinkFile -Path 'C:\Data\my_awesome.log' | # Tell logger to write log messages into file
    Start-Logger

# Test all log levels
Write-VerboseLog 'Test verbose message'
Write-DebugLog 'Test debug message'
Write-InfoLog 'Test info message'
Write-WarningLog 'Test warning message'
Write-ErrorLog 'Test error message'
Write-FatalLog 'Test fatal message'

Close-Logger

poshlog_example_fullversion

For detailed documentation see wiki

You can(and you should) log formatted data:

Write-InfoLog 'Current date and time is {DateTime}' -PropertyValues (Get-Date)

# Some example data
$position = @{
    Latitude = 25
    Longitude = 134
}
$elapsedMs = 34

Write-InfoLog 'Processed {@Position} in {Elapsed:000} ms.' -PropertyValues $position, $elapsedMs

poshlog_example_simplest_console

Fluent API is too bulky? You don't need extra sinks? Use short setup version(logs into console and file):

# Create and start new logger
Start-Logger -FilePath 'C:\Data\my_awesome.log' -Console

Write-InfoLog 'Hurrray, my first log message!'

# Don't forget to close the logger
Close-Logger

poshlog_example_simplest_console

Extendability

PoShLog is extensible just like Serilog. All available extensions can be found here.

Documentation

These examples are just to get you started fast. For more detailed documentation please check wiki.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Show your support

  • ⭐ Star the PoShLog repository. This is the least you can do to support this project.
  • 👍 Give us some feedback or suggest features using Discussions or discord
  • 🔎 Test PoShLog and raise issues
  • Contribute 🚀 you can start with good first issues

Contributors

Building Locally

  1. Install PoShLog.Tools

     Install-Module -Name PoShLog.Tools -Force -Verbose -Scope CurrentUser
    
  2. Import PoShLog.Tools

     Import-Module -Name PoShLog.Tools
    
  3. Bootstrap the required modules

     Bootstrap '.\cd\RequiredModules.psd1'
    
  4. Run the build script

     Invoke-Build '.\src\PoShLog.Build.ps1' -Configuration '(Dev/Prod)' -Task Clean, BuildDependencies, CopyModuleFiles -ModuleVersion "$(MajorVersion).$(MinorVersion).$(BugfixVersion)"
    

Authors

Release Notes

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

poshlog's People

Contributors

bradyshober avatar gitbute avatar tomasbouda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

poshlog's Issues

Set-DefaultMessageFormatter cmdlet isn't available in the latest release as referenced.

You can alter ouputted message using Set-DefaultMessageFormatter cmdlet.

(From here: https://github.com/PoShLog/PoShLog/wiki/Write-DebugLog)

When I try to use Set-DefaultMessageFormatter I get a 'Set-DefaultMessageFormatter' is not recognized as a name of a cmdlet... error. There is a little icon next to the example that has a 2.2.0+ badge. But I don't see anywhere I can attain that version of this module.

Any help would be great.

Support for Azure Application Insights Sink

Your PS module looks awesome. Thank BTW!
I'd like to use Azure Application Insights Sink. I was looking over your Http Sink as an example of how I'd attempt to contribute a PR supporting this sink. Is the build/packaging process as simple simple as calling your build.ps1? Any thoughts on where I may run into issues? Thanks!!

Set ValueFromPipelineByPropertyName=$True for parameters

I like using splats for setting parameters on functions, the code is cleaner and easier to comment and read. Setting ValueFromPipelineByPropertyName=$True for parameters allows spats to be used. I tested this by modifying my installation of PoSHLog but it changes so many files I didn't think a pull request was appropriate.

Here's your sample code i modified to use splats:

$ScriptName = 'TestLogging'

# FileSink Settings
$fileSink = @{
	# Log to user's AppData\Local directory
	Path = "$($ENV:LocalAppData)\$($ScriptName)-.log"
	RollingInterval = 'Day' # Infinite | Year | Month | Day | Hour | Minute
	# Roll on file size AND day
	RollOnFileSizeLimit = $true
	RetainedFileCountLimit = 5
}

New-Logger |
    Set-MinimumLevel -Value Verbose |
    Add-SinkFile @fileSink |
    Add-SinkConsole |
    Start-Logger

# Test all log levels
Write-VerboseLog 'Test verbose message'
Write-DebugLog 'Test debug message'
Write-InfoLog 'Test info message'
Write-WarningLog 'Test warning message'
Write-ErrorLog 'Test error message'
Write-FatalLog 'Test fatal message'

# Example of formatted output
$position = @{
    Latitude = 25
    Longitude = 134
}
$elapsedMs = 34

Write-InfoLog 'Processed {@Position} in {Elapsed:000} ms.' -PropertyValues $position, $elapsedMs

Close-Logger

How to get current log file

Ahoj, jak zjistím do jakého souboru aktuálně zapisuje?

$LogPath = "c:\tmp\"
New-Logger -verbose | 
            Set-MinimumLevel -Value Verbose | 
            Add-SinkFile -Path "$($LogPath)test-.log" -RollingInterval Day -OutputTemplate '{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}' | 
            #Add-SinkConsole | 
            Start-Logger

neco jako:
(Get-Logger).sinkfile.filepath > c:\tmp\test-20201230.log

Edit by @TomasBouda - translation for EN users:
Hi, how to I get current log file?

$LogPath = "c:\tmp\"
New-Logger -verbose | 
            Set-MinimumLevel -Value Verbose | 
            Add-SinkFile -Path "$($LogPath)test-.log" -RollingInterval Day -OutputTemplate '{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}' | 
            #Add-SinkConsole | 
            Start-Logger

something like:
(Get-Logger).sinkfile.filepath > c:\tmp\test-20201230.log

Release of json formatting in console logs?

I saw that back in November, JsonFormatter in a console log was implemented. Is there any chance a version of the module with that feature could be published to powershell gallery?

Getting double output with the "Short version"

Start-Logger -MinimumLevel Verbose -Console

Write-VerboseLog "Test verbose message"
Write-DebugLog "Test debug message"
Write-InfoLog "Test info message"
Write-WarningLog "Test warning message"
Write-ErrorLog "Test error message"
Write-FatalLog "Test fatal message"

Close-Logger

Results with this on Pwsh:

Code_I937b5kps4

How can I suppress the duplicates?

Note: The "Full version" works as expected:

New-Logger | Set-MinimumLevel -Value Verbose | Add-SinkConsole | Start-Logger

Write-VerboseLog "Test verbose message"
Write-DebugLog "Test debug message"
Write-InfoLog "Test info message"
Write-WarningLog "Test warning message"
Write-ErrorLog "Test error message"
Write-FatalLog "Test fatal message"

Close-Logger

Code_YFsRMlpSD6

Any help would be fantastic.

[Feature Request] Implement conditional sink

When using logger with multiple sinks, in my use case it's SinkFile and SinkSeq.
I would like to have the ability to filter which messages goes to SinkSeq,
Depending on some condition (LogEvent property or some context/input I could pass when writing the log).

Thank.

Unable to load one or more of the requested types

Attempting to Import-Module PoShLog causes the following string of errors:


PS C:\Users\Administrator> import-module poshlog
Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more
information.
At C:\Program Files\WindowsPowerShell\Modules\poshlog\2.1.1\functions\internal\Add-PackageTypes.ps1:9 char:4
+             Add-Type -Path $path
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeComma
   nd

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more
information.
At C:\Program Files\WindowsPowerShell\Modules\poshlog\2.1.1\functions\internal\Add-PackageTypes.ps1:9 char:4
+             Add-Type -Path $path
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeComma
   nd

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more
information.
At C:\Program Files\WindowsPowerShell\Modules\poshlog\2.1.1\functions\internal\Add-PackageTypes.ps1:9 char:4
+             Add-Type -Path $path
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeComma
   nd

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more
information.
At C:\Program Files\WindowsPowerShell\Modules\poshlog\2.1.1\functions\internal\Add-PackageTypes.ps1:9 char:4
+             Add-Type -Path $path
+             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
    + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeComma
   nd

Unable to find type [Serilog.Formatting.Display.MessageTemplateTextFormatter].
At C:\Program Files\WindowsPowerShell\Modules\poshlog\2.1.1\PoShLog.psm1:19 char:25
+ ... Formatter = [Serilog.Formatting.Display.MessageTemplateTextFormatter] ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Serilog.Formatt...teTextFormatter:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

Environment information:


PS C:\Users\Administrator> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.3866
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.3866
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Any suggestions as to what might help here?

What is or should be the behavior of PowerShell sink with -Debug or -Verbose switch.

I created a sample script to illustrate the outputs of a logger with both Console and PowerShell sinks :

[CmdletBinding()]
param()

Import-Module -Name PoShLog
New-Logger | 
	Set-MinimumLevel -Value Verbose |
	Add-SinkPowerShell -OutputTemplate "SinkPowerShell : {Message:lj}" | 
	Add-SinkConsole -OutputTemplate "SinkConsole : {Message:lj}{NewLine}" | 
	Start-Logger 
Write-Host "VERBOSE"
Write-VerboseLog "Test Verbose message : ($($VerbosePreference))"
Write-Host "DEBUG"
Write-DebugLog "Test Debug message : ($($DebugPreference))"
Write-Host "INFO"
Write-InfoLog "Test Information message : ($($InformationPreference))"
Write-Host "WARNING"
Write-WarningLog "Test Warning message : ($($WarningPreference))"
Write-Host "ERROR"
Write-ErrorLog "Test Error message"
Write-Host "FATAL"
Write-FatalLog "Test Fatal message."

Close-Logger

When I execute this script with default values for preferences variables and without any switch for Verbose, Debug, ... here is the output :

image

If I execute the script with a -Verbose switch (or another one), I thought the Verbose level output would be displayed by the PowerShell sink. It isn't whereas the value of the associated preference variable has actually changed to Continue :

image

If I set the $VerbosePreference variable to Continue before executing the script (or use the -ToParameters switch in ````Set-MinimumLevel``` the verbose log is displayed by the PowerShell sink.

image

Is this behavior normal ? If yes, what am I understanding wrong ?

Console sink cannot handle debug and verbose messages in PowerShell

Hi

Found another bug in console sink.
Write-VerboseLog as well as Write-DebugLog never outputs to console.
I tried with $VerbosePreference 'Continue' as well as with a function call -Verbose.

Best regards

Edit:
A possible solution could be:
In Write-VerboseLog, check if console sink is active and if it is, output the Message to Write-Verbose.

[Feature Request] Add ability to write JSON formatted logs to console sink

I see that the file sink has the ability to write JSON formatted logs, we are looking for the same functionality on the console sink so that we can produce structured logs on stdout when running a PowerShell container.

I'm going to start poking at what it would take to do this, but if you have any information you can throw my way, that would be appreciated.

Write-*Log CmdLets do not support pipeline input

I would like to be able to pipe the output of CmdLets or called programs into Write-*Log. Currently, only the last element of the input gets actually logged.

New-Logger | Add-SinkConsole | Start-Logger
'Foo', 'Bar', 'Baz' | Write-InfoLog
Close-Logger

Expected:

[13:37:00 INF] Foo
[13:37:00 INF] Bar
[13:37:00 INF] Baz

# Or

[13:37:00 INF] Foo
Bar
Baz

Actual:

[13:37:00 INF] Baz

This is due to the CmdLets using ValueFromPipeline for the $MessageTemplate parameter but not wrapping the execution body in a Process block. Basically, all that needs to be done is replace this

Write-Log -MessageTemplate $MessageTemplate -Logger $Logger -Exception $Exception -ErrorRecord $ErrorRecord -PropertyValues $PropertyValues -PassThru:$PassThru

with this in all the CmdLets:

Process {
    Write-Log -MessageTemplate $MessageTemplate -Logger $Logger -Exception $Exception -ErrorRecord $ErrorRecord -PropertyValues $PropertyValues -PassThru:$PassThru
}

I can open a PR if you are interested in this.
Also big props for this nice project 👍.

Console sink outputting to wrong streams

Hi

Another problem in the console sink are streams. Right now it seems it doesnt use any Powershell streams at all. Test with *> $null which should hide every stream. The log messages still get displayed.

I think it would be nice to have the corresponding LogLevels also write to the correct powershell stream.

Best regards

Console sink throws error on initialization when used in VSCode PS integrated console preview

Hi there

First up, cool module you have here!
I ran into following error upon installing v 2.0.0 from powershellgallery,
and trying to use it in VSCodes Powershell integrated console:

(PowerShell 5.1, Server 2016,
=====> PowerShell Preview Integrated Console v2020.6.1 <=====)

New-Logger |
    Add-SinkFile -Path 'C:\Data\my_awesome.log' |
    Add-SinkConsole |
    Start-Logger
Cannot find an overload for "Console" and the argument count: "7".
At C:\Program Files\WindowsPowerShell\Modules\PoshLog\2.0.0\functions\sinks\Add-SinkConsole.ps1:50 char:3
+         $LoggerConfig = [Serilog.ConsoleLoggerConfigurationExtensions ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

It works in the normal console tho

PowerShell Core support?

Hi, thanks for this brilliant project. Example works well, all looks good and straightforward.

Wonder if there are plans to support PowerShell Core.
Could not get it running with PS Core 6.2, not sure why - didn't dig deeper.

Name                           Value
----                           -----
PSVersion                      6.2.3
PSEdition                      Core
GitCommitId                    6.2.3
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.