c#实现服务器性能监控并发送邮件保存日志

Posted IT在线自学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#实现服务器性能监控并发送邮件保存日志相关的知识,希望对你有一定的参考价值。

客户端代码

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Management;
using System.Configuration;
using System.Net;
using System.IO;

namespace MON.WS
{
    public partial class Service : ServiceBase
    {
        //post 11.9
        //卸载服务
        //installutil /u F:\XLFX-2\XLFX\MON.WS\bin\debug\MON.WS.EXE
        //安装服务
        //installutil F:\XLFX-2\XLFX\MON.WS\bin\debug\MON.WS.EXE
        object threadObj;
        Thread jobThread;
        Dictionary<string, PerformanceCounter> dicCounter;
        Dictionary<string, ManagementObject> dicDisk;

public Service()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            threadObj = new object();
            dicCounter = new Dictionary<string, PerformanceCounter>();
            dicDisk = new Dictionary<string, ManagementObject>();
            jobThread = new Thread(new ThreadStart(Job));
            jobThread.IsBackground = true;
            jobThread.Start();
        }
        /// <summary>
        /// 服务停止
        /// </summary>
        protected override void OnStop()
        {
            if (jobThread.IsAlive)
            {
                jobThread.Abort();
                jobThread.Join();
            }
            foreach (var obj in dicCounter.Values)
            {
                obj.Dispose();
            }
            foreach (var obj in dicDisk.Values)
            {
                obj.Dispose();
            }
            dicDisk.Clear();
            dicCounter.Clear();
        }



服务端代码

代码如下:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Threading
Imports System.Collections.Generic
Imports System.Text

' 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class MONService
    Inherits System.Web.Services.WebService

<WebMethod()> _
    Public Function GetMachineConfig(ByVal HostName As String, ByVal IP1 As String, ByVal IP2 As String) As DataSet
        Dim sqlda As New data_source.WebTao.Public.SqlServerData
        Try
            Dim sSQL As String = "select *  from mon_server_list " & _
                " where S_HOSTNAME ='" & HostName & "' and IP1 = '" & IP1 & "'  and IP2 = '" & IP2 & "'"
            Dim dt As DataTable = sqlda.GetMytable(sSQL)
            If dt.Rows.Count < 1 Then
                sqlda.runSql("insert into mon_server_list (S_HOSTNAME,IP1,IP2,S_ISWATCH,CICODE,S_NAME,CAMP_ID,S_KIND,STATUS) values ('" & HostName & "','" & IP1 & "','" & IP2 & "',0,'待确定','待确定',-1,0,0)")
                dt = sqlda.GetMytable(sSQL)
                sqlda.runSql("INSERT INTO [MON_INFO] ([LIST_ID],[S_CPU],[S_DISK_APP],[S_DISK_SYS],[S_MEMORY],[S_FLOW_IN],[S_FLOW_OUT],[S_WEB_PORT],[S_SQL_CONNECT],[IN_TIME]) VALUES (" & dt.Rows(0)("LIST_ID").ToString() & ",-1,-1,-1,-1,-1,-1,-1,-1,'" & Now.ToString() & "') ")
            End If
            Dim result As DataSet = sqlda.GetMyDataSet("select * from MON_PARAMETER")
            result.Tables.Add(dt)
            Return result
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    <WebMethod()> _
    Public Function UpdateServerStatus(ByVal ParamArray ValueArr() As String)
        Dim sqlda As New data_source.WebTao.Public.SqlServerData
        Try
            Dim sSQL As String = "UPDATE [MON_INFO] " & _
                  " SET " & _
                  " [S_CPU] = " & ValueArr(1) & _
                  " ,[S_DISK_APP] = " & ValueArr(2) & _
                  " ,[S_DISK_SYS] = " & ValueArr(3) & _
                  " ,[S_MEMORY] = " & ValueArr(4) & _
                  " ,[S_FLOW_IN] = " & ValueArr(5) & _
                  " ,[S_FLOW_OUT] = " & ValueArr(6) & _
                  " ,[S_WEB_PORT] = " & ValueArr(7) & _
                  " ,[S_SQL_CONNECT] = " & ValueArr(8) & _
                  " ,[IN_TIME] = '" & Now.ToString() & "'" & _
                  " WHERE LIST_ID = " & ValueArr(0)
            sqlda.runSql(sSQL)
            '没有策略
            If ValueArr(9).Trim() = "-1" Or String.IsNullOrEmpty(ValueArr(9).Trim()) Then
                Return 0
            End If
            '找到策略
            sSQL = "select * from MON_CAMPAIGN_LIST where CAMP_ID = " & ValueArr(9)
            Dim dt As DataTable = sqlda.GetMytable(sSQL)
            Dim Dic As New Dictionary(Of String, String)
            Dic.Add("S_PRIORITY", dt.Rows(0)("S_PRIORITY").ToString())
            Dic.Add("S_ACTION", dt.Rows(0)("S_ACTION").ToString())

'验证策略
            sSQL = "select count(*) from MON_INFO where 1=1 and " & dt.Rows(0)("S_NAME").ToString & " and LIST_ID = " & ValueArr(0)
            Dim FLAG = CType(sqlda.myExecuteScalar(sSQL), Integer)
            '没有超标
            If FLAG < 1 Then
                Return 0
            End If

'是否到了下一个轮训间隔
            sSQL = "select TOP 1 * from [MON_MAIL]   WHERE list_id = " & ValueArr(0) & "  ORDER BY S_SENDTIME DESC "
            dt = sqlda.GetMytable(sSQL)
            Dim ts As TimeSpan = TimeSpan.MaxValue
            If dt.Rows.Count > 0 Then
                Dim thatTime As DateTime = CType(dt.Rows(0)("S_SENDTIME"), DateTime)
                ts = DateTime.Now.Subtract(thatTime)
            End If
            sSQL = "select * from MON_PARAMETER"
            dt = sqlda.GetMytable(sSQL)
            Dim circ As Integer = CType(dt.Rows(0)("MAIL_CIRC"), Integer)
            If ts.TotalSeconds < circ Then
                Return 0
            End If

'异步发信
            Dic.Add("S_TITLE", dt.Rows(0)("S_TITLE").ToString())
            Dic.Add("MAIL_SMTP_SERVER", dt.Rows(0)("MAIL_SMTP_SERVER").ToString())
            Dic.Add("MAIL_ACCOUNT", dt.Rows(0)("MAIL_ACCOUNT").ToString())
            Dic.Add("MAIL_PASSWORD", dt.Rows(0)("MAIL_PASSWORD").ToString())
            Dic.Add("MAIL_FROM", dt.Rows(0)("MAIL_FROM").ToString())
            Dic.Add("MAIL_ADDRESS", dt.Rows(0)("MAIL_ADDRESS").ToString())
            Dim sout As Double
            Dim sin As Double
            Try
                sin = Convert.ToDouble(ValueArr(5)) / 1024.0
                sout = Convert.ToDouble(ValueArr(6)) / 1024.0
            Catch ex As Exception
                sin = -1
                sout = -1
            End Try
            Dim sb As New StringBuilder()
            sb.AppendFormat("CPU使用率:{0}%<br />", ValueArr(1))
            sb.AppendFormat("内存使用率:{0}%<br />", ValueArr(4))
            sb.AppendFormat("系统磁盘使用率:{0}%<br />", ValueArr(3))
            sb.AppendFormat("文件磁盘使用率:{0}%<br />", ValueArr(2))
            sb.AppendFormat("网络下行流量IN:{0}KB/S<br />", sin.ToString())
            sb.AppendFormat("网络上行流量OUT:{0}KB/S<br />", sout.ToString())
            sb.AppendFormat("网站连接数:{0}<br />", ValueArr(7))
            sb.AppendFormat("数据库连接数:{0}<br />", ValueArr(8))
            Dim subject As String = String.Format("人力运营管理系统监控告警:{0}{1}", ValueArr(10), IIf(ValueArr(11) = "0", "WEB服务器", "数据库服务器"))
            Dim body As String = String.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}", DateTime.Now.ToString(), Dic("S_PRIORITY"), Dic("S_TITLE"), sb.ToString(), Dic("S_ACTION"))
            'TODO:oracle不支持~select @@identity
            sSQL = "INSERT INTO [MON_MAIL] ([LIST_ID] ,[S_SOURCE] ,[S_CONTENT] ,[S_ACTION] ,[S_PRIORITY] ,[S_ADDRESS] ,[STATUS] ,[S_SENDTIME]) VALUES " & _
            "(" & ValueArr(0) & ",'" & Dic("S_TITLE") & "','" & sb.ToString() & "','" & Dic("S_ACTION") & "','" & Dic("S_PRIORITY") & "','" & dt.Rows(0)("MAIL_ADDRESS").ToString() & "',0,'" & DateTime.Now.ToString() & "');select @@identity"
            Dim index As Integer = CType(sqlda.myExecuteScalar(sSQL), Integer)

Dic.Add("SUBJECT", subject)
            Dic.Add("BODY", body)
            Dic.Add("INDEX", index)
            Dic.Add("CONSTR", sqlda.GetMyConnStr())

ThreadPool.QueueUserWorkItem(AddressOf SendMail, Dic)
        Catch ex As Exception

End Try
    End Function
End Class


以上是关于c#实现服务器性能监控并发送邮件保存日志的主要内容,如果未能解决你的问题,请参考以下文章

C# 创建日志系统

python发送邮件

zabbix监控Exchange服务器邮件队列

python 监控日志并发送邮件报警

linux性能指标

zabbix监控无法发送邮件到指定的邮箱