PowerShell中实现一个最基本的日志器logger

举报
jcLee95 发表于 2023/06/08 21:45:15 2023/06/08
【摘要】 PowerShell中实现一个最基本的日志器logger 李俊才 的 CSDN 博客 邮箱 :291148484@163.com CSDN 主页:https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343 本文地址:https://blog.csdn.net/qq_28550263/article/details/124024540目 ...
PowerShell中实现一个最基本的日志器logger

李俊才 的 CSDN 博客
邮箱 :291148484@163.com
CSDN 主页https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343
本文地址https://blog.csdn.net/qq_28550263/article/details/124024540

目 录

1. 场景介绍

2. 代码实现

3. 使用示例


1. 场景介绍

Powershell 是 IT 运维中绕不过去的一个语言,它不仅能在Windows中使用,同样也适用于Linux。对于运维人员来说,虽然不需要像后端开发人员一样制作日志器以记录大量的生产数据,但也同样存在记录某些运行过程的需求。

本文实现一个简单的Logger,但我们再运维中使用脚本自动化启停服务,测试系统运行状态,执行脚本时,可以通过该Logger方便地输出记录相应地信息,清晰地标注日志等级和记录发生的时间。

2. 代码实现

#*****************************************************************************
# Copyright Jack Lee. All rights reserved.
# Licensed under the MIT License.
# Email: 291148484@163.com
# https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343
#*****************************************************************************

class Logger {
    [string]$Lines
    [string]$SavePath
    [bool]$log

    Logger([string]$SavePath){
        $this.Lines = '';
        $this.log = $True;
        $this.SavePath = $SavePath;
    }

    Logger([string]$SavePath, [bool]$log){
        $this.Lines = '';
        $this.log = $log;
        $this.SavePath = $SavePath;
    }
    
    [string]getDataTime(){
        return  Get-Date -Format 'yyyy-MM-dd hh:mm:ss'
    }

    [void]writeLog($color,$logmessages)
    {
        write-host -ForegroundColor $color $logmessages
        $logmessages >> $this.SavePath
    }

    [void]Trace($s){
        $msg = $this.getDataTime() + " [TRACE] " + $s
        if ($this.log){
            $this.writeLog('DarkGreen',$msg)
        }
    }

    [void]Info($s){
        $msg = $this.getDataTime() + " [INFO] " + $s
        if ($this.log){
            $this.writeLog('Gray',$msg)
        }
    }

    [void]Debug($s){
        $msg = $this.getDataTime() + " [DEBUG] " + $s
        if ($this.log){
            $this.writeLog('DarkBlue',$msg)
        }
    }

    [void]Warn($s){
        $msg = $this.getDataTime() + " [WARN] " + $s
        if ($this.log){
            $this.writeLog('Yellow',$msg)
        }
    }

    [void]Error($s){
        $msg = $this.getDataTime() + " [ERROR] " + $s
        if ($this.log){
            $this.writeLog('Red',$msg)
        }
    }

    [void]Critical($s){
        $msg = $this.getDataTime() + " [CRITICAL] " + $s
        if ($this.log){
            $this.writeLog('Magenta',$msg)
        }
    }
}

3. 使用示例

3.1 基本使用

【例】简单测试各个日志方法的使用,代码如下:

$SavePath = 'C:\Users\Administrator\Desktop\mylog.log';

$logger = [Logger]::new($SavePath);
$logger.Trace('tracetracetrace')
$logger.Info('InfoInfoInfo')
$logger.Debug('debugdebugdebug')
$logger.Warn('warnwarnwarn')
$logger.Error('errorerrorerror')
$logger.Critical('criticalcriticalcritical')

其效果如图:
1.png

其中mylog.log是运行该ps1脚本后所生产的历史日志记录,使用 VSCode 等工具打开,可以看到高亮显示的输出日志如图所示:

2.png

注意:如果你想要像使用 bat 脚本那样运行 ps1 脚本,需要设置执行策略,你可以先使用Get-ExecutionPolicy查看你当前的执行策略:

Get-ExecutionPolicy

将执行策略设置为 Unrestricted 以直接运行ps1脚本:

Set-ExecutionPolicy Unrestricted

3.2 实例:检测网络情况,自动重启适配器并记录日志

【需求介绍】
Windows 系统上的网络适配器出现问题时,可能导致服务器与外界无法通信。有时,这种故障将会随着网络适配器的重启而解决。
手动打开 网络与贡献中心 => 高级网络配置

3.png

图:Windows Server 2016 网络适配器界面

4.png

图:Windows 11 网络适配器界面

你当然可以在这里手动点击 禁用(Disable),然后再手动点击 启用(Enable)。但是设想当一台服务器运行时,人工发现网络适配器故障需要重启比较缓慢,我们希望一旦电掉线则自动地重启某个网络适配器,以此减小由于网络适配器故障(假定每次重启后一定可以恢复)带来生产上更大的损失,这时我们可以考虑使用定时测试网络的方式。

  • 执行某次定时任务时,先尝试 Ping 某个正常情况下可以Ping 通的主机;
  • 若本次Ping测试顺利,则网络正常,无需重启网络适配器,日志记录测试成功,程序结束;
  • 若本次Ping测试失败,输出Ping失败到日志,尝试先禁用网络适配器;
  • 若网络适配器禁用成功,输出禁用成功到日志,并执行启用刚刚禁用的网络适配器;
  • 若网络适配器禁用失败,输出失败信息到日志,程序结束;
  • 若禁用成功且启用仍然成功,则重启网络适配器全过程顺利执行完成,程序结束。

【代码实现】

function Main(){
    $tracepath='C:\tmp\restart_jboss';
    $SavePath = "$tracepath\$env:COMPUTERNAME _restartNetAdapter.log";
    $logger = [Logger]::new($SavePath);
    $adapterName = 'Ethernet0 2'
    
    
    Ping www.baidu.com;
    if($?){
        $logger.Info('Pingִ Execution succeeded.')
    }
    else{
        $logger.Warn('Pingִ Execution failed, attempting to restore the network adapter.')
        $logger.Info('Disable NetAdapter...');
        
        Disable-NetAdapter -Name $adapterName;
        if($?){
            $logger.Info('The network adapter has been disabled');
            $logger.Info('Enable NetAdapter...');

            Enable-NetAdapter -Name $adapterName;
            if($?){
                $logger.Info('The network adapter is enabled.')
            }else{
                $logger.Critical('Failed to enable the network adapter, which requires manual processing.');
            }
        }
        else{

        }
    }
};

Main
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。