Real-time log monitoring and alarm small instance of ActiveMQ message queue and SignalR, activemqsignalr

Source: Internet
Author: User

Real-time log monitoring and alarm small instance of ActiveMQ message queue and SignalR, activemqsignalr

Main technologies:

Log4net-generate logs.

ActiveMQ-send messages when generating logs and monitor logs in real time.

SignalR-display ActiveMQ monitoring logs to the browser in real time without refreshing the browser.

Introduction to small instances:

Name System 1 on the left and System 2 on the right

System 1 is a log generation tool. System 2 displays data in real time based on the generated logs. If there are more than 50 logs at the ERROR level, an alarm is displayed in real time.

System code analysis:

1. Message Queue-message sending Method

Public class ActiveMQHelper
{

Private IConnectionFactory factory;

/// <Summary>

/// Initialize the ActiveMQ Factory

/// </Summary>

Public ActiveMQHelper ()

{

Try

{

// Initialize the factory. The default URL here does not need to be modified.

Factory = new ConnectionFactory ("tcp: // localhost: 61616 ");

}

Catch (Exception ex)

{

New LogHelper (typeof (ActiveMQHelper). Fatal (string. Format ("Message Queue Server initialization failed"), ex );

}

}

/// <Summary>

/// Message sending Method

/// </Summary>

/// <Param name = "msg"> </param>

Public void CreateConnection (string msg)

{

// Establish a connection through the factory

Using (IConnection connection = factory. CreateConnection ())

{

// Create a Session through a connection

Using (ISession session = connection. CreateSession ())

{

// Create a producer through a session. The new method shows the Queue in MQ.

IMessageProducer prod = session. CreateProducer (new Apache. NMS. ActiveMQ. Commands. ActiveMQQueue ("LogsQueue "));

// Create a message object

ITextMessage message = prod. CreateTextMessage ();

// Assign the actual message to this object

Message. Text = msg;

// Set the attributes of the message object. This is very important. It is the filter condition of Queue and the unique attribute specified by P2P messages.

Message. Properties. SetString ("filter", "log ");

// The producer sends messages out. The following enumerated parameters are used to determine whether the MsgDeliveryMode is a long chain. The MsgPriority parameter gives priority to messages, and the minimum sending unit. Of course, there are other reloads.

Prod. Send (message, MsgDeliveryMode. Persistent, MsgPriority. Normal, TimeSpan. MinValue );

}

}

}

}

2. Send a message when generating the error Log

System 2 main code analysis:

1. Page code

SignalR Introduction: the reason why the browser can load data without refreshing the facts depends on SignalR. Javascript Functions are dynamically generated in the background. You can call the functions generated in the background on the page.

Call the MyHub. cs class constructor in the background. The call method is var chat = $. connection. myHub. If you use SignalR, please search for relevant information.

 

2. Background code MyHub. cs class:

Note: The following gray line of code is a dynamically generated javascript dynamic function.

Clients. All. addNewMessageToPage (json); // function to be called on the foreground page

 

Public class MyHub: Hub

{

Public delegate void DelegateRevMessage (ITextMessage message );
Private static string logPath = ConfigHelper. getreceivetting ("logpath ");

Public MyHub ()
{

Var index = new Random (). Next (1, 1,100 );
// Create a connection Factory
IConnectionFactory factory = new ConnectionFactory ("tcp: // localhost: 61616 ");
// Build a connection through the factory
Apache. NMS. IConnection connection = factory. CreateConnection ();
// This is the name of the connected Client
Connection. ClientId = "LogsQueueListener" + index;
// Start the connection. actively start the connection if listening
Connection. Start ();
// Create a session through a connection
ISession session = connection. CreateSession ();
// Create a consumer through a session. This is the listener parameter setting of the session type such as Queue.
IMessageConsumer consumer = session. CreateConsumer (new Apache. NMS. ActiveMQ. Commands. ActiveMQQueue ("LogsQueue"), "filter = 'log '");
// Register a listener event
Consumer. Listener + = new MessageListener (consumer_Listener );

}

Void consumer_Listener (IMessage message)
{

ITextMessage msg = (ITextMessage) message;
DelegateRevMessage delegateRev = RevMessage;

IAsyncResult result = delegateRev. BeginInvoke (msg, null, null );
DelegateRev. EndInvoke (result );

}

/// <Summary>
/// Real-Time Message Queue Monitoring Method
/// </Summary>
/// <Param name = "message"> </param>
Public void RevMessage (ITextMessage message)
{

// Message. Text: the value in the message queue.
List <LogInfoModel> list = this. Analysis (DateTime. Now );
If (list! = Null & list. Count> 0)
{

Var fatalList = list. Where (x => x. Level. ToLower () = LevelEnum. FATAL. AsString (). ToLower (). ToList ();
Var errorList = list. Where (x => x. Level. ToLower () = LevelEnum. ERROR. AsString (). ToLower (). ToList ();

/*
* Alarm operations can be handled based on the log level and log quantity.
* For example, if (fatalList. Count> 0) {// send an email; // reminder; // send a text message, etc.} // if there is a fatal-level log, an alert is immediately triggered;
* Or if (errorList. Count> 50) {// send an email; // reminder; // send a text message, etc.} // if there are more than 50 logs at the error level, an alert is immediately triggered;
***/

Var json = new {fatalCount = fatalList. Count, errorCount = errorList. Count };
Clients. All. addNewMessageToPage (json); // function to be called on the foreground page

}

}

/// <Summary>
/// Obtain the log list of the current day Based on the date
/// </Summary>
/// <Param name = "date"> </param>
/// <Returns> </returns>
Public List <LogInfoModel> Analysis (DateTime date)
{

Var loganalysis = new LogAnalysisBll ();
Var month = date. Month. ToString ();
Var day = date. Day. ToString ();
Month = month. Length = 1? "0" + month: month;
Day = day. Length = 1? "0" + day: day;

// Analyze logs based on the Log Path to obtain the list
Var list = loganalysis. getLog (string. format ("{4} {0} \ {1} \ {2} \ {3 }. log ", date. year, month, date. day, date. toString ("yyyyMMdd"), logPath ));
Return list;

}

}

 

Note: I have just started to study ActiveMQ and SignalR. If there is anything wrong with ActiveMQ and SignalR, I hope the experts can provide more guidance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.