1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Slack boltをTypescriptで作成時、log4jsで作成したログファイルにログを書き出す

Posted at

#これはなに

Slack bolt公式リファレンスのログ拡張方法がTypescriptに対応していなかったため備忘もかねて作成しました。
https://slack.dev/bolt/ja-jp/concepts#logging

こちらにサンプルも記載しましたのでよかったらご確認にどうぞ。
https://github.com/attumkwg/slackboltlogbytypescript

またこの記事に記載のソースコードは以下Yuta Ohigashi様の記事とリポジトリを参考に作成しています。
Bolt + jsx-slack + TypeScript を使って Slack App をつくる
https://github.com/phigasui/slack_app_boilerplate

#内容

対応方法は単純で@slack/logger内に存在するConsoleLoggerを拡張してやるだけです。

import dotenv from 'dotenv'
import { App } from '@slack/bolt'
import Log4js from 'log4js'
import { LogLevel, ConsoleLogger } from '@slack/logger'

dotenv.config()

Log4js.configure('./src/log/log4js.json')

const systemLogger = Log4js.getLogger('system')

// @slack/loggerにConsoleLoggerというclassが存在するのでそれを拡張する
class CustomLogger extends ConsoleLogger {
  debug(...msg: any[]): void {
    systemLogger.debug(JSON.stringify(msg))
  }
  info(...msg: any[]): void {
    systemLogger.info(JSON.stringify(msg))
  }
  warn(...msg: any[]): void {
    systemLogger.warn(JSON.stringify(msg))
  }
  error(...msg: any[]): void {
    systemLogger.error(JSON.stringify(msg))
  }
}

const customLogger = new CustomLogger()
customLogger.setLevel(LogLevel.DEBUG)

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  logger: customLogger
})

log4js.json
{
    "appenders": {
        "ConsoleLogAppender": {
            "type": "console"
        },
        "SystemLogAppender": {
            "type": "dateFile",
            "filename": "./log/system.log",
            "pattern": ".yyyy-MM-dd",
            "daysToKeep": 7
        }
    },
    "categories": {
        "default": {
            "appenders": ["ConsoleLogAppender"],
            "level": "all"
        },
        "system": {
            "appenders": ["SystemLogAppender"],
            "level": "debug"
        }
    }
}

こうしてやることでsystem.logに下記のようなslack appの通信ログが記録されるようになります。

system.log
[2020-02-11T18:12:22.340] [DEBUG] system - ["apiCall('views.open') start"]
[2020-02-11T18:12:22.340] [DEBUG] system - ["will perform http request"]
[2020-02-11T18:12:22.711] [DEBUG] system - ["http response received"]
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?