SysLog RFC5424 的正则表达式 [英] Regular Expression for SysLog RFC5424

查看:71
本文介绍了SysLog RFC5424 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 SysLog 服务器,我的程序在其中接收 RFC5424Format 的消息.

I am writing a SysLog Server where my program receive messages of RFC5424Format.

我的程序必须解析消息并存储值.

My program has to parse the message and store the values.

我有一个无法解析消息的正则表达式.

I have got a regular expression which is failing to parse the message.

正则表达式有问题.我是正则表达式的新手.

There is problem in Regular Expression.I am new to Regular expression.

感谢任何帮助.

public static void Main()
    {
        string RFC5424Format = @"(\<(?<PRI>\d+)\>(?<VERSION>\d+)?)? \ * (?<TIMESTAMP> ( (?<YEAR>\d+) - (?<MONTH>\d+) - (?<DAY>\d+) ) T+ (?<HOUR>\d+): (?<MINUTE>\d+): (?<SECOND>\d+) (\.(?<MILLISECONDS>\d+))? (?<OFFSET>Z|(\+|\-)\d+:\d+)? ) \ (?<HOSTNAME>[\w!-~]+) \ (?<APPNAME>[\w!-~]+) \ (?<PROCID>[\w!-~]+) \ (?<MSGID>[\w!-~]+) \  (?<SD>-|(\[.*\])) \ ?(?<MESSAGE>.*)?";

        Regex rfc5424 = new Regex("^" + RFC5424Format + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace);

        string input = "< 38 > 1 2018 - 03 - 01T16: 05:51.799465 + 05:30 AAEINBLR07229L Source_UDP - -\n ??? MessageContent_Via_UDP - 5424";

        Match m = rfc5424.Match(input);

        if (m.Success)
        {
            Console.WriteLine("Regex is fine");
        }
        else
        {
            Console.WriteLine("Problem in Regex");
        }
    }

推荐答案

我最近刚遇到这个问题.根据 RFC 5424,系统日志消息应采用以下格式:HEADERSP STRUCTURED-DATA [SP MSG],其中 SP 是一个空格字符,括号表示数据是可选的.话虽如此,我发现将消息分解为三个单独的正则表达式模式,然后在实例化 Regex 用于比较的对象.

I just came across this problem recently. According to RFC 5424, the Syslog message should be in the following format: HEADER SP STRUCTURED-DATA [SP MSG], where SP is a space character and the brackets represent the data is optional. Having said that I found it easier to break the message down into three separate regular expression patterns and then combine them when I instantiate a Regex object for comparing.

这是我的示例课程.我希望它有所帮助.

Here's my sample class. I hope it helps.

public class SyslogMessage
{
    private static readonly string _SyslogMsgHeaderPattern = @"\<(?<PRIVAL>\d{1,3})\>(?<VERSION>[1-9]{0,2}) (?<TIMESTAMP>(\S|\w)+) (?<HOSTNAME>-|(\S|\w){1,255}) (?<APPNAME>-|(\S|\w){1,48}) (?<PROCID>-|(\S|\w){1,128}) (?<MSGID>-|(\S|\w){1,32})";
    private static readonly string _SyslogMsgStructuredDataPattern = @"(?<STRUCTUREDDATA>-|\[[^\[\=\x22\]\x20]{1,32}( ([^\[\=\x22\]\x20]{1,32}=\x22.+\x22))?\])";
    private static readonly string _SyslogMsgMessagePattern = @"( (?<MESSAGE>.+))?";
    private static Regex _Expression = new Regex($@"^{_SyslogMsgHeaderPattern} {_SyslogMsgStructuredDataPattern}{_SyslogMsgMessagePattern}$", RegexOptions.None, new TimeSpan(0, 0, 5));

    public int Prival { get; private set; }
    public int Version { get; private set; }
    public DateTime TimeStamp { get; private set; }
    public string HostName { get; private set; }
    public string AppName { get; private set; }
    public string ProcId { get; private set; }
    public string MessageId { get; private set; }
    public string StructuredData { get; private set; }
    public string Message { get; private set; }
    public string RawMessage { get; private set; }

    /// <summary>
    /// Parses a Syslog message in RFC 5424 format. 
    /// </summary>
    /// <exception cref="FormatException"></exception>
    /// <exception cref="OverflowException"></exception>
    /// <exception cref="ArgumentNullException"></exception>
    /// <exception cref="InvalidOperationException"></exception>
    public static SyslogMessage Parse(string rawMessage)
    {
        if (string.IsNullOrWhiteSpace(rawMessage)) { throw new ArgumentNullException("message"); }

        var match = _Expression.Match(rawMessage);
        if (match.Success)
        {
            return new SyslogMessage
            {
                Prival = Convert.ToInt32(match.Groups["PRIVAL"].Value),
                Version = Convert.ToInt32(match.Groups["VERSION"].Value),
                TimeStamp = Convert.ToDateTime(match.Groups["TIMESTAMP"].Value),
                HostName = match.Groups["HOSTNAME"].Value,
                AppName = match.Groups["APPNAME"].Value,
                ProcId = match.Groups["PROCID"].Value,
                MessageId = match.Groups["MSGID"].Value,
                StructuredData = match.Groups["STRUCTUREDDATA"].Value,
                Message = match.Groups["MESSAGE"].Value,
                RawMessage = rawMessage
            };
        }
        else { throw new InvalidOperationException("Invalid message."); }
    }

    public override string ToString()
    {
        var message = new StringBuilder($@"<{Prival:###}>{Version:##} {TimeStamp.ToString("yyyy-MM-ddTHH:mm:ss.fffK")} {HostName} {AppName} {ProcId} {MessageId} {StructuredData}");

        if (!string.IsNullOrWhiteSpace(Message))
        {
            message.Append($" {Message}");
        }

        return message.ToString();
    }
}

这篇关于SysLog RFC5424 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆