前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >06Prism WPF 入门实战 - Log&控件库

06Prism WPF 入门实战 - Log&控件库

作者头像
JusterZhu
发布2022-12-07 20:02:10
6800
发布2022-12-07 20:02:10
举报
文章被收录于专栏:JusterZhuJusterZhu

1.概要

源码及PPT地址:https://github.com/JusterZhu/wemail

视频地址:https://www.bilibili.com/video/BV1KQ4y1C7tg?share\source=copy\web

本章分为以下几个部分来了解:

Part1 日志

Part1.1 全局异常捕捉

Part1.2 Dump

Part2 引入控件库

2.详细内容

Part1 日志

(1)Nuget安装:

Microsoft.Extensions.Logging.Abstractions

NLog.Extensions.Logging

NLog.Config

(2)配置Nlog.config

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="info"
      throwException ="true"
      internalLogFile="logs/internal-nlog.txt">    //日志的错误位置文件

  <variable name="logDirectory" value="${basedir}/logs"/>
  <!-- the targets to write to -->
  <targets async="true">
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="${logDirectory}/nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="${logDirectory}/nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    <!--|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}-->


    <!-- write log message to database -->
    <!--<target name="db"  xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">-->
    <target type="Database" name="db" dbProvider="Npgsql.NpgsqlConnection,Npgsql"    《这里的数据库名字注意查找》connectionString="Database=backofficev2;Host=*;User Id=*;Password=*;pooling=false;port=*;">
      <commandText>  //使用postgresql 这里的字段要加双引号,timestamp要将string类型的转换为timestamp类型
        INSERT INTO "SystemLog"("Source","Level","Content","CreatedAt") VALUES(@source, @level, @content, TO_TIMESTAMP(@createdAt, 'YYYY-MM-DD HH24:MI:SS'));
      </commandText> 
      <!-- database connection parameters  ${logger}  Server-->   <-数据库中要写的字段->
      <parameter name="@source" layout="Server" />
      <parameter name="@level" layout="${level}" />
      <parameter name="@content" layout="${message}" />
      <parameter name="@createdAt" layout="${date}" />
    </target>
    <!--</target>-->

  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
   <!--TRACE,DEBUG,INFO,WARN,ERROR,FATAL警告级别控制-->  
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <!--INFO,WARN,ERROR,FATAL-->
    <logger name="AiEcgWebApi.Controllers.*" minlevel="Warn" writeTo="db" />
    <!--DEBUG,INFO,WARN,ERROR,FATAL-->
    <logger name="*" minlevel="Debug" writeTo="ownFile-web" />   
  </rules>
</nlog>

(3)App.cs注入log组件

代码语言:javascript
复制
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    var factory = new NLog.Extensions.Logging.NLogLoggerFactory();
    Microsoft.Extensions.Logging.ILogger logger = factory.CreateLogger("NLog");
    containerRegistry.RegisterInstance(logger);
}

(4)ViewModel构造函数获取log引用

代码语言:javascript
复制
public MainWindowViewModel(ILogger logger)
{
     logger.LogInformation("hhhhhhh");
}

Part1.1 全局异常捕捉

出错的任务中未观察到的异常将触发异常呈报策略时出现。

代码语言:javascript
复制
/// <summary>
/// 应用程序启动时创建Shell
/// </summary>
/// <returns></returns>
protected override Window CreateShell()
{
    //UI线程未捕获异常处理事件
    this.DispatcherUnhandledException += OnDispatcherUnhandledException;
    //Task线程内未捕获异常处理事件
    TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
    //多线程异常
    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; 
    return Container.Resolve<MainWindow>();
}

Part1.2 Dump

程序异常崩溃前使用此类为进程创建DUMP文件,之后可以使用WinDbg等工具进行分析。(该文件包含一些敏感信息切勿将公司项目中的dump文件公布到互联网上)

Windebug分析案例:

https://mp.weixin.qq.com/s/i6cJHTrIPweDIplzzfHnVQ

Windebug分析教程:

https://docs.microsoft.com/zh-cn/windows-hardware/drivers/debugger/getting-started-with-windows-debugging?WT.mc_id=WDIT-MVP-5004326

Windebug命令:

https://docs.microsoft.com/zh-cn/windows-hardware/drivers/debugger/commands?WT.mc_id=WDIT-MVP-5004326

Part2 控件库

代码语言:javascript
复制
1.Nuget安装:MaterialDesignInXamlToolkit

2.选择主题
Light theme:<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
Dark theme:   <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml" />

3.App文件:
<Application x:Class="MaterialTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
            </ResourceDictionary.MergedDictionaries>            
        </ResourceDictionary>
    </Application.Resources>
</Application>

4.配置View
<Window [...]
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.FontWeight="Medium"
        TextElement.FontSize="14"
        FontFamily="pack://application:,,,/MaterialDesignThemes.Wpf;component/Resources/Roboto/#Roboto"
        [...] >
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-11-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JusterZhu 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.概要
  • 2.详细内容
相关产品与服务
日志服务
日志服务(Cloud Log Service,CLS)是腾讯云提供的一站式日志服务平台,提供了从日志采集、日志存储到日志检索,图表分析、监控告警、日志投递等多项服务,协助用户通过日志来解决业务运维、服务监控、日志审计等场景问题。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档