Opserver 初探二《exceptions配置》


上一節主要介紹Opserver的搭建以及redis、sqlserver監控的配置,本節主要介紹異常日志的記錄和監控。要實現異常日志的監控我們需要在項目中引入StackExchange.Exceptional組件,用於日志的采集和存儲操作。

首先我們簡單的來認識一下Opserver項目config文件夾下的ExceptionsSettings.json.example文件,

{
  "warningRecentCount": "100",           //警告提醒最近條目數,當超出該值在頭部高亮顯示警告
  "criticalRecentCount": "200",          //嚴重警告提醒最近條目數,當超出該值在頭部高亮顯示嚴重警告
  "viewGroups": "StatusExceptionsRO",    //安全模式“ad"下的分組查看權限設置
  // You can have a simple applications list here, or a grouped structure when dealing with many apps.
  //"applications": [                    //產生異常日志的程序
  //  "Core",
  //  "Chat",
  //  "Stack Auth",
  //  "StackExchange.com",
  //  "API",
  //  "API v2",
  //  "Area 51",
  //  "Status",
  //  "Push Server",
  //  "Sockets",
  //  "Careers",
  //  "BackOffice",
  //  "Control Panel"
  //],

//以分組在形式歸類異常日志,未在groups定義的在others中顯示
"groups": [ { "name": "Core Q&A", "applications": [ "Core", "Chat", "Stack Auth", "StackExchange.com", "API v2", "Sockets", "Area 51", "Open ID", "Stack Server", "StackSnippets", "Status" ] }, { "name": "Careers", "applications": [ "Careers", "BackOffice", "BackOffice", "Control Panel", "StackShop", "CareersAuth" ] }, { "name": "Mobile", "applications": [ "Push Server" ] }, { "name": "Ads & Data", "applications": [ "Prov Read API" ] } ], "stores": [ //異常日志存儲位置 { "name": "New York", "queryTimeoutMs": 2000, "pollIntervalSeconds": 10, "connectionString": "Server=ny-sql03.ds.stackexchange.com;Database=NY.Exceptions;Integrated Security=SSPI;" } ] }

 

 

1、StackExchange.Exceptional引入及記錄異常日志

異常日志可以有web,console,service等程序產生

web項目,需要3步配置:

  • 在web項目中nuget安裝StackExchange.Exceptional組件(依賴dapper)
  • 在web.config中增加section “Exceptional
<section name="Exceptional" type="StackExchange.Exceptional.Settings" />
<Exceptional applicationName="Samples.MVC4">
  <ErrorStore type="Memory" />
<!--連接opserver數據庫時開啟-->
<!--<ErrorStore type="SQL" connectionString="Server=.;Database=Exceptions;Uid=Exceptions;Pwd=myPassword!" />-->
</Exceptional>

applicatinName 產生異常日志的程序名稱用於Opserve顯示歸類

ErrorStore 錯誤存儲有4種實現方式,Memory,JSON,SQL,MySQL,參考官方說明

    <!-- Which ErrorStore to use, if no element is declared here a Memory store with defaults will be used -->
    <!--<ErrorStore type="Memory" />-->
    <!-- Other store types, common attributes:
         - rollupSeconds: optional (default 600 seconds), determines how long the window is to roll up exceptions with the same stack trace - 0 to not roll up
         - backupQueueSize: optional (default 1000), determines how many errors to cache (excluding rollups) in memory when logging fails...every 2 seconds we'll retry logging and flush these out to the final store -->
    <!-- JSON: size defaults to 200, this is how many files are kept before the oldest error is removed -->
    <!--<ErrorStore type="JSON" path="~/Errors" size="200" />-->
    <!-- SQL: only a connection string or connection string name is needed, many applications can log to the same place as long as they have unique names (otherwise we can't tell them apart). -->
    <!--<ErrorStore type="SQL" connectionString="Server=.;Database=Exceptions;Uid=Exceptions;Pwd=myPassword!" />-->
    <!--<ErrorStore type="SQL" connectionStringName="MyConnectionString" />-->
    <!-- You can also use a MySQL Database with the MySQL ErorrStore -->
    <!--<ErrorStore type="MySQL" connectionString="Server=.;Database=Exceptions;Username=Exceptions;Pwd=myPassword!" />-->
    <!--<ErrorStore type="MySQL" connectionStringName="MyConnectionString" />-->

 

  • 在web.config中增加handler和module,module配置后,異常日志自動記錄
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <!-- OPTIONAL: if not using a router, or you don't want to access the errors directly via this application,
           this is not necessary.  A common scenario for this is logging all errors to a common SQL store and viewing
           them through another application or a dashboard elsewhere.  
           Note: If the error list isn't exposed in the application, any errors in logging exceptions will be queued up, 
           but not visible (since that's exposed on the error list view).
      -->
      <add name="Exceptional" path="exceptions.axd" verb="POST,GET,HEAD" type="StackExchange.Exceptional.HandlerFactory, StackExchange.Exceptional" preCondition="integratedMode" />
    </handlers>
    <!-- Here the error log needs to be registered to catch all unhandled exceptions, 
         these are exceptions that make it all the way to being a 500 page the user sees. -->
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="StackExchange.Exceptional.ExceptionalModule, StackExchange.Exceptional" />
    </modules>
  </system.webServer>

 console,service前兩步同web項目,需要nuget安裝StackExchange.Exceptional,在app.config配置section“Exceptional”,然后在main主函數中添加未處理異常記錄

        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
             /*
             ...
             */
         }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                StackExchange.Exceptional.ErrorStore.LogExceptionWithoutContext(ex);
            }
        }

 如果需要自定義添加異常,可以在try...catch中記錄,如:

           try
            {
                throw new Exception("Just a try/catch test");
            }
            catch (Exception ex)
            {
                // logged, but caught so we don't crash
                ErrorStore.LogExceptionWithoutContext(ex);
            }

 

3、異常數據存儲SQL,創建表語句

USE [OpServerTest]
GO

/****** Object:  Table [dbo].[Exceptions]    Script Date: 2016/11/16 16:28:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Exceptions](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [GUID] [uniqueidentifier] NOT NULL,
    [ApplicationName] [nvarchar](50) NOT NULL,
    [MachineName] [nvarchar](50) NOT NULL,
    [CreationDate] [datetime] NOT NULL,
    [Type] [nvarchar](100) NOT NULL,
    [IsProtected] [bit] NOT NULL,
    [Host] [nvarchar](100) NULL,
    [Url] [nvarchar](500) NULL,
    [HTTPMethod] [nvarchar](10) NULL,
    [IPAddress] [varchar](40) NULL,
    [Source] [nvarchar](100) NULL,
    [Message] [nvarchar](1000) NULL,
    [Detail] [nvarchar](max) NULL,
    [StatusCode] [int] NULL,
    [SQL] [nvarchar](max) NULL,
    [DeletionDate] [datetime] NULL,
    [FullJson] [nvarchar](max) NULL,
    [ErrorHash] [int] NULL,
    [DuplicateCount] [int] NOT NULL,
 CONSTRAINT [PK_Exceptions] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Exceptions] ADD  DEFAULT ((0)) FOR [IsProtected]
GO

ALTER TABLE [dbo].[Exceptions] ADD  DEFAULT ((1)) FOR [DuplicateCount]
GO

 

4、在Opserver項目中,配置 ExceptionsSettings.json文件,修改groups和stores,如:

"stores": [      //異常日志存儲位置
    {
      "name": "ExceptionDB",
      "queryTimeoutMs": 2000,
      "pollIntervalSeconds": 10,
      "connectionString": "Data Source=192.168.1.120;User ID=sa;Password=*******;Initial Catalog=OpserverTest;"
    }


注:目前Opserver版本支持store在sql server服務器上,不支持在文件,內存,和Mysql中,如果需要mysql支持,需要修改Opserver.core代碼。
      在配置多個store的情況,默認第一個有效

 官方示例dome和源碼下載:https://github.com/NickCraver/StackExchange.Exceptional


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM