如何快速解析Apache日志文件?

4
假设我有一个日志文件,已经分割成字符串数组。例如,我有以下这些行。
123.4.5.1 - - [03/Sep/2013:18:38:48 -0600] "GET /products/car/ HTTP/1.1" 200 3327 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36"
123.4.5.6 - - [03/Sep/2013:18:38:58 -0600] "GET /jobs/ HTTP/1.1" 500 821 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20100101 Firefox/23.0"
我可以使用典型的字符串操作来解析它们,但我认为可以用正则表达式更好地完成。我试图遵循python中某人使用的类似模式,但我无法完全弄清楚。以下是我的尝试。
这是模式: ([(\d.)]+) - - [(.?)] "(.?)" (\d+) - "(.?)" "(.?)" 当我尝试使用它时,没有匹配项。
let lines = contents.split(separator: "\n")
            let pattern = "([(\\d\\.)]+) - - \\[(.*?)\\] \"(.*?)\" (\\d+) - \"(.*?)\" \"(.*?)\""
            let regex = try! NSRegularExpression(pattern: pattern, options: [])
            for line in lines {
                let range = NSRange(location: 0, length: line.utf16.count)
                let parsedData = regex.firstMatch(in: String(line), options: [], range: range)
                print(parsedData)
            }

如果我能将数据提取到一个模型中,那将是最好的。我需要确保代码具有高性能和快速性,因为可能会有成千上万行需要考虑。

预期结果

let someResult = (String, String, String, String, String, String) or 
let someObject: LogFile = LogFile(String, String, String...)

我希望将解析的行分解为其各个部分。 IP操作系统操作系统版本浏览器浏览器版本等。 对数据进行任何真正的解析都足够了。

1
这看起来更像是一个Apache日志文件。 - Martin R
@MartinR 是的,那是我的笔误。已经更正了。 - xTwisteDx
3个回答

5

根据您展示的样本,您可以尝试以下操作:

^((?:\d+\.){3}\d+).*?\[([^]]*)\].*?"([^"]*)"\s*(\d+)\s*(\d+)\s*"-"\s*"([^"]*)"$

上述正则表达式的在线演示

说明:对上述内容进行详细说明。

^(                   ##Starting a capturing group checking from starting of value here.
   (?:\d+\.){3}\d+   ##In a non-capturing group matching 3 digits followed by . with 1 or more digits
)                    ##Closing 1st capturing group here.
.*?\[                ##Matching non greedy till [ here.
([^]]*)              ##Creating 2nd capturing group till ] here.
\].*?"               ##Matching ] and non greedy till " here.
([^"]*)              ##Creating 3rd capturing group which has values till " here.
"\s*                 ##Matching " spaces one or more occurrences here.
(\d+)                ##Creating 4th capturing group here which has all digits here.
\s*                  ##Matching spaces one or more occurrences here.
(\d+)                ##Creating 5th capturing group here which has all digits here.
\s*"-"\s*"           ##Spaces 1 or more occurrences "-" followed by spaces  1 or more occurrences " here.
([^"]*)              ##Creating 6th capturing group till " here.
"$                   ##Matching " at last.

2
你显然是一个正则表达式大神。这个解决方案可行。 - xTwisteDx

2

正确的正则表达式模式是由@RavinderSingh13提供的,但我还想添加一下我所做的,以使它在我的代码中正常运行,以便其他人可以在未来使用它,而不必在StackOverflow上搜索所有答案。

我需要找到一种方法将Apache日志文件解析为Swift中可用的对象。代码如下。

实现扩展

extension String {
    func groups(for regexPattern: String) -> [[String]] {
        do {
            let text = self
            let regex = try NSRegularExpression(pattern: regexPattern)
            let matches = regex.matches(in: text,
                                        range: NSRange(text.startIndex..., in: text))
            return matches.map { match in
                return (0..<match.numberOfRanges).map {
                    let rangeBounds = match.range(at: $0)
                    guard let range = Range(rangeBounds, in: text) else {
                        return ""
                    }
                    return String(text[range])
                }
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
}

创建模型对象

class EventLog {
    let ipAddress: String
    let date: String
    let getMethod: String
    let statusCode: String
    let secondStatusCode: String
    let versionInfo: String
    
    init(ipAddress: String, date: String, getMethod: String, statusCode: String, secondStatusCode: String, versionInfo: String ){
        self.ipAddress = ipAddress
        self.date = date
        self.getMethod = getMethod
        self.statusCode = statusCode
        self.secondStatusCode = secondStatusCode
        self.versionInfo = versionInfo
    }
}

解析数据

我想指出正则表达式模式返回一个 [[String]],因此您必须从返回的总体组中获取子组。类似于解析 JSON。

func parseData() {
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let destinationFileUrl = documentsUrl.appendingPathComponent("logfile.log")
        
        do {
            let contents = try String(contentsOf: destinationFileUrl, encoding: .utf8)
            let lines = contents.split(separator: "\n")
            let pattern = "^((?:\\d+\\.){3,}\\d).*?\\[([^]]*)\\].*?\"([^\"]*)\"\\s*(\\d+)\\s+(\\d+)\\s*\"-\"\\s*\"([^\"]*)\"$"
            for line in lines {
                let group = String(line).groups(for: pattern)
                let subGroup = group[0]
                let ipAddress = subGroup[1]
                let date = subGroup[2]
                let getMethod = subGroup[3]
                let statusCode = subGroup[4]
                let secondStatusCode = subGroup[5]
                let versionInfo = subGroup[6]
                
                DispatchQueue.main.async {
                    self.eventLogs.append(EventLog(ipAddress: ipAddress, date: date, getMethod: getMethod, statusCode: statusCode, secondStatusCode: secondStatusCode, versionInfo: versionInfo))
                }
            }
        } catch {
            print(error.localizedDescription)
        }
    }

1

该模式没有匹配,因为在连字符的位置上有 1+ 个数字。

为了使该模式更具性能,您可以使用 否定字符类 "([^"]*)" 来捕获例如在 " 之间除 " 以外的任何字符。

(\d+(?:\.\d+)+) - - \[([^\]\[]+)\] "([^"]*)" (\d+) (\d+) "[^"]+" "([^"]+)"
  • (\d+(?:\.\d+)+) 捕获组1,匹配1个或多个数字,重复1个或多个.和1个或多个数字
  • - - 直接匹配
  • \[([^\]\[]+)\] 匹配[,捕获组2中匹配1个或多个除[]以外的任意字符,然后匹配]
  • "([^"]*)" 匹配",捕获组3中匹配1个或多个非"的任意字符,然后匹配"
  • (\d+) (\d+) 捕获组4和5匹配1个或多个数字
  • "[^"]+" 与前面的机制相同,用于匹配",但只匹配
  • "([^"]+)" 与前面的机制相同,用于匹配",在捕获组6中匹配1个或多个非"的任意字符

正则表达式演示 | Swift 演示

示例代码

let pattern = #"(\d+(?:\.\d+)+) - - \[([^\]\[]+)\] "([^"]*)" (\d+) (\d+) "[^"]+" "([^"]+)""#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"123.4.5.1 - - [03/Sep/2013:18:38:48 -0600] "GET /products/car/ HTTP/1.1" 200 3327 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
    var groups: [String] = []
    for rangeIndex in 1 ..< match.numberOfRanges {
        groups.append((testString as NSString).substring(with: match.range(at: rangeIndex)))
    }
    if !groups.isEmpty {
        result.append(groups)
    }
}
print(result)

输出

[["123.4.5.1", "03/Sep/2013:18:38:48 -0600", "GET /products/car/ HTTP/1.1", "200", "3327", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36"]]

我不确定为什么无法让这个模式起作用。每当我尝试使用它时,都会抛出一个无效的正则表达式错误。 - xTwisteDx
@xTwisteDx 我看到了,你必须在字符类\[([^\]\[]+)\]中转义方括号。我已经更新了答案。 - The fourth bird

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接