代码之家  ›  专栏  ›  技术社区  ›  jl6

使用PostgreSQL解析Apache日志

  •  2
  • jl6  · 技术社区  · 14 年前

    This O'Reilly article 给出了一个分析Apache日志行的PostgreSQL语句示例:

     INSERT INTO http_log(log_date,ip_addr,record)
         SELECT CAST(substr(record,strpos(record,'[')+1,20) AS date),
                CAST(substr(record,0,strpos(record,' ')) AS cidr),
                record
     FROM tmp_apache;
    

    显然,这只提取IP和时间戳字段。是否有从典型的组合日志格式记录中提取所有字段的规范语句?如果没有,我会写一个,我保证将结果发布在这里!

    2 回复  |  直到 14 年前
        1
  •  3
  •   jl6    14 年前

    好的,这是我的解决方案:

    insert into accesslog
    select m[1], m[2], m[3],
        (to_char(to_timestamp(m[4], 'DD/Mon/YYYY:HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS ')
            || split_part(m[4], ' ',2))::timestamp with time zone,
         m[5], m[6]::smallint, (case m[7] when '-' then '0' else m[7] end)::integer, m[8], m[9] from (
        select regexp_matches(record,
     E'(.*) (.*) (.*) \\[(.*)\\] "(.*)" (\\d+) (.*) "(.*)" "(.*)"')
     as m from tmp_apache) s;
    

    它从表tmp_apache中提取原始日志行,并将字段(使用regexp)提取到数组中。

        2
  •  -1
  •   jmz    14 年前

    this blog post 有关登录Postgres的信息。

    推荐文章