LoginSignup
0
0

More than 1 year has passed since last update.

node.jsでGZIP圧縮された複数のログファイルを処理

Posted at

目的

  • Apacheログなど、GZIPされた複数のログ(テキスト)ファイルを処理する時のサンプル
  • すべてのログをなめてから処理をしたい場合に、非同期のせいで勝手に次のステップに進むのに悩まされた
  • 大容量のログファイルに対応するため、1行ずつデータを読み込む処理にした

コード

処理内容

  • 指定したディレクトリにあるGZIPファイルの一覧を生成
  • 一覧にあるファイルをひとつずつ開いて処理、分析に必要なデータはグローバル変数に追加
  • ファイルを全部読み終わったら適宜処理
"use strict";

/*
* Modules
*/

import fs from 'fs';
import log4js from 'log4js';
import zlib from 'zlib';
import readline from 'readline';
import { format } from 'util';

/*
* Config
*/

const SRC_FILE_DIR = "./src_files";

/*
* Logger
*/

const logger = log4js.getLogger()
logger.level = 'all'

/*
* readline
*/

const rl = (path) => readline.createInterface({
    input: fs.createReadStream(path).pipe(zlib.createGunzip()),
    crlfDelay: Infinity
});

/*
* 行の変換
*/

const parseLine = (line)=>{

    // ここに行単位での処理内容を記載・結果はグローバル変数に入れる
    
}

/*
* グローバル変数
*/

var count_lines_all = 0;
var count_files = 0;

/*
* Main
*/

logger.info('Start Processing.');

(async () => {

    var src_files = fs.readdirSync(SRC_FILE_DIR);
    for (var src_file of src_files) {

        // ファイルの読込を開始
        count_files++;
        var count_lines_in_file = 0;
        await (async () => {
            for await (const line of rl(`src_files/${src_file}`)) {
                count_lines_in_file++;
                parseLine(line);

            }
            logger.info(format("File Parsed: [%s] %s - %s Lines", count_files.toString().padStart(4, 0), src_file, count_lines_in_file));
            count_lines_all += count_lines_in_file;

        })();
    }
    logger.info(`File Parsed: Total: ${count_lines_all} Lines.`);

    // 全体を通した分析を記述

})();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0