简体   繁体   English

模块和点源脚本中的Powershell日志记录

[英]Powershell Logging within modules and dot sourced scripts

I have a few functions stored in a .psm1 file that is used by several different ps1 scripts. 我在.psm1文件中存储了一些功能,该文件由几个不同的ps1脚本使用。 I created a logging function (shown below), which I use throughout these ps1 scripts. 我创建了一个日志记录功能(如下所示),在整个这些ps1脚本中都使用了该功能。 Typically, I import the module within a script by simply calling something like: 通常,我可以通过简单地调用以下命令将模块导入脚本中:

Import-Module $PSScriptRoot\Module_Name.psm1

Then within the module, I have a write logger function: 然后在模块中,我有一个写记录器功能:

Write-Logger -Message "Insert log message here." @logParams

This function is used throughout the main script and the module itself. 整个主脚本和模块本身都使用此功能。 The splatting parameter @logParams is defined in my main .ps1 file and is not explicitly passed to the module, I suppose the variables are implicitly within the module's scope upon being imported. @logParams参数@logParams是在我的主.ps1文件中定义的,并且未显式传递给模块,我假设变量在导入时隐式位于模块范围内。 What I have works, but I feel like it isn't a great practice. 我的作品行得通,但我觉得这不是一个好习惯。 Would it be better practice to add a param block within my module to require @logParams to be explicitly passed from the main .ps1 script? 最好在模块中添加一个param块,以要求从.ps1主脚本中显式传递@logParams吗? Thanks! 谢谢!

function Write-Logger() {
    [cmdletbinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [string]$Path,
        [Parameter(Mandatory=$true)]
        [string]$Message,
        [Parameter(Mandatory=$false)]
        [string]$FileName = "Scheduled_IDX_Backup_Transcript",
        [switch]$Warning,
        [switch]$Error
    )
    # Creates new log directory if it does not exist
    if (-Not (Test-Path ($path))) {
        New-Item ($path) -type directory | Out-Null
    }

    if ($error) {
        $label = "Error"
    }
    elseif ($warning) {
        $label = "Warning"    
    }
    else {
        $label = "Normal"
    }

    # Mutex allows for writing to single log file from multiple runspaces
    $mutex = new-object System.Threading.Mutex $false,'MutexTest'
    [void]$mutex.WaitOne()
    Write-Host "$(Format-LogTimeStamp) $label`: $message"
    "$(Format-LogTimeStamp) $label`: $message" | Out-file "$path\$fileName.log" -encoding UTF8 -append
    [void]$mutex.ReleaseMutex()
}

I have this code in ps1 that I dot source into scripts where I want to produce my own logs. 我在ps1中有这段代码,可以将源点到要生成自己的日志的脚本中。 The ps1 contains the simpleLogger class as well as the routine below that creates a global variable. ps1包含simpleLogger类以及下面的创建全局变量的例程。 The script can be dot sourced again and the global variable value passed to subsequently spawned jobs to maintain a single log file. 脚本可以再次以点为源,并将全局变量值传递给随后产生的作业以维护单个日志文件。

class simpleLogger
{
    [string]$source
    [string]$target
    [string]$action
    [datetime]$datetime
    hidden [string]$logFile = $global:simpleLog

    simpleLogger()
    {
        $this.datetime = Get-Date
    }

    simpleLogger( [string]$source, [string]$target, [string]$action )
    {
        $this.action = $action
        $this.source = $source
        $this.target = $target
        $this.datetime = Get-Date
    }

    static [simpleLogger] log( [string]$source, [string]$target, [string]$action )
    {
        $newLogger = [simpleLogger]::new( [string]$source, [string]$target, [string]$action )
        do {
            $done = $true
            try {
                $newLogger | export-csv -Path $global:simpleLog -Append -NoTypeInformation
            }
            catch {
                $done = $false
                start-sleep -milliseconds $(get-random -min 1000 -max 10000)
            }
        } until ( $done )
        return $newLogger
    }
}

if( -not $LogSession ){

    $global:logUser = $env:USERNAME
    $global:logDir = $env:TEMP + "\"
    $startLog = (get-date).tostring("MMddyyyyHHmmss")
    $global:LogSessionGuid = (New-Guid)
    $global:simpleLog = $script:logDir+$script:logUser+"-"+$LogSessionGuid+".log"
    [simpleLogger]::new() | export-csv -Path $script:simpleLog -NoTypeInformation
    $global:LogSession = [simpleLogger]::log( $script:logUser, $LogSessionGuid, 'Log init' )

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM