Use sqlinfomessageeventhandler to obtain the print or error message in SQL.

Source: Internet
Author: User

When writing SQL stored procedures, we often use print to print some information for debugging and debugging stored procedures.

However, once our application is deployed, we want to record the print information in the stored process to help us quickly diagnose application errors.

In this way, we need to get the SQL print information from the application, which describes how to use sqlinfomessageeventhandler to get this information (in fact, I wrote an English http://blog.csdn.net/farawayplace613/article/details/5667245 last year ).

 

The following is a step-by-step aggregation (assuming you already have the SQL instance database northwind ):

1. Execute the following statement in northwind to create a stored procedure for testing sqlinfomessageeventhandler (this stored procedure is only responsible for printing some messages, sqlinfomessageeventhandler will process these messages)

-- =============================================-- This procedure is used for testing SqlInfoMessageEventHandler -- =============================================-- Drop stored procedure if it already existsIF EXISTS (  SELECT *     FROM INFORMATION_SCHEMA.ROUTINES    WHERE SPECIFIC_SCHEMA = N'dbo'     AND SPECIFIC_NAME = N'TestPrintMessage' )   DROP PROCEDURE dbo.TestPrintMessage GOCREATE PROCEDURE dbo.TestPrintMessage ASPrint 'Warning: This is a warning message test' Print 'Error: This is a error message ' Print 'Critical: This is critical message' Print 'Verbose: This is verbose message' Print 'Information: This is information message' select 'test' GO

2. Create a console application to call the preceding stored procedure and use sqlinfomessageeventhandler to process the Print message.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Diagnostics;using System.Data.SqlClient;using System.Data;namespace TestSqlTrace{    class Program    {        static void Main(string[] args)        {            using (SqlConnection sqlCon = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))            {                sqlCon.InfoMessage += new SqlInfoMessageEventHandler(OnReceivingInfoMessageFromSql);                SqlCommand cmd = new SqlCommand("dbo.TestPrintMessage", sqlCon);                cmd.CommandType = CommandType.StoredProcedure;                sqlCon.Open();                cmd.ExecuteNonQuery();            }            Console.WriteLine("Press any key to exist!");            Console.Read();        }        /// <summary>         /// The event handler for the InfoMessage event.         /// </summary>         /// <param name="sender">The sender.</param>         /// <param name="e">The event arguments.</param>        private static void OnReceivingInfoMessageFromSql(object sender, SqlInfoMessageEventArgs e)        {            string prevLogMessage = String.Empty;            Regex traceLevelPattern = new Regex(@"^(Warning|Error|Critical|Verbose|Information):", RegexOptions.IgnoreCase);                       foreach (SqlError err in e.Errors)            {                string errMessage = err.Message;                string logMessage = errMessage;                TraceEventType level = TraceEventType.Verbose;                Match m = traceLevelPattern.Match(errMessage);                if (m.Success)                {                    try                    {                        level = (TraceEventType)Enum.Parse(typeof(TraceEventType), m.Result("$1"));                    }                    catch (ArgumentException ae)                    {                        Console.WriteLine(ae.Message);                    }                    logMessage = errMessage.Substring(m.Result("$1:").Length);                                   }                if (prevLogMessage != logMessage)                {                                      prevLogMessage = logMessage;                    Console.WriteLine("level:" + level + "; message:" + logMessage);                }                            }                               }     }}

3. Execute the above program

Generally, these print messages are recorded in the log file. As for how to write the messages to the log file, it is an amazing thing.

 

 

 

 

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.