Logstash將解析的日誌插入MySQL數據庫

1.首先Logstash需要安裝logstash-output-jdbc插件(以下方式基於docker)
Dockerfile如下:

FROM logstash:7.4.0
RUN sed -i 's#https://rubygems.org#https://gems.ruby-china.com#g' Gemfile && logstash-plugin install logstash-output-jdbc

2.解析nginx日誌

        date {
                match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"]   #解析時間
        }
        urldecode {
                field => "Http_Request"     #請求日誌轉爲中文
        }
        geoip {     #獲取IP插件
                database => "/usr/share/logstash/geodb/GeoLite2-City.mmdb"
                source => "Client_IP"
                target => "geoip"
                fields => ["country_name","region_name", "city_name", "ip", "longitude", "latitude", "location"]
                add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
                add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
        } 
        useragent {   #解析用戶瀏覽器特徵
                source => "User_Agent"
                target => "ua"
        }
        mutate {     #日誌必要處理
                convert => [ "[geoip][coordinates]", "float" ]
                convert => [ "Http_Status_Code", "integer" ]
                convert => [ "Http_Bytes", "integer" ]
                convert => [ "Request_Time", "float" ]
                convert => [ "Upstream_Response_Time", "float" ]
                remove_field => [ "beat", "@version", "auth", "prospector", "source", "offset"]
                gsub =>["timestamp","\ \+0800",""]    #將時間的+0800進行刪除
                gsub =>["User_Agent","\"",""]  #將瀏覽器的雙引號去除

        }
output {
        jdbc {
                connection_string => "jdbc:mysql://mysql/elk?user=root&password=123456&useUnicode=true&characterEncoding=UTF8"
                driver_jar_path => "/usr/share/logstash/geodb/mysql-connector-java-8.0.18.jar"    #主意加載mysql連接器
                statement => ["INSERT INTO nginx_access_log(Client_IP,X_Forwarded_For,time,App_Version,Device,Device_Name,System_Version,Http_Method,Site,Http_Request,Http_Status_Code,Http_Referrer,Usercode,NetType,Openudid,Request_Time,Upstream_Response_Time,User_agent,city,province) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)","Client_IP","X_Forwarded_For","timestamp","App_Version","Device","Device_Name","System_Version","Http_Method","Site","Http_Request","Http_Status_Code","Http_Referrer","Usercode","NetType","Openudid","Request_Time","Upstream_Response_Time","User_Agent","[geoip][city_name]","[geoip][region_name]"]
#此處注意,比如需要插入城市信息[geoip][city_name]
        }
}               
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章