GCP 外のアプリケーションのログを Stackdriver Logging で集める
2020/02/27 18:29:212021/09/02 01:29:51
logging
にしました GCP_SERVICE_ACCOUNT
のような名前で発行された json のキーを設定します。 install.sh
$ yarn add bunyan @google-cloud/logging-bunyan
$ yarn add -D @types/bunyan
logger.ts
import $ from "transform-ts"
export const serviceAccount = $.obj({
type: $.string,
project_id: $.string,
private_key_id: $.string,
private_key: $.string,
client_email: $.string,
client_id: $.string,
auth_uri: $.string,
token_uri: $.string,
auth_provider_x509_cert_url: $.string,
client_x509_cert_url: $.string,
}).transformOrThrow(JSON.parse(process.env.GCP_SERVICE_ACCOUNT))
logger.ts
import { LoggingBunyan } from "@google-cloud/logging-bunyan"
import { name } from '../package.json'
export const loggingBunyan = new LoggingBunyan({
logName: name,
projectId: serviceAccount.project_id,
credentials: {
client_email: serviceAccount.client_email,
private_key: serviceAccount.private_key,
},
resource: {
type: "gae_app",
labels: {
project_id: serviceAccount.project_id,
module_id: name,
version_id: process.env.HEROKU_SLUG_COMMIT || "",
zone: "",
},
},
serviceContext: process.env.HEROKU_SLUG_COMMIT
? {
service: name,
version: process.env.HEROKU_SLUG_COMMIT,
}
: {},
})
gae_app
を採用しているのがコツです。 logging_log
などでは Error Reporting が発火しないので注意してください。 logger.ts
export const getLogger = (s: string) => {
return bunyan.createLogger({
name: s.replace(`${__dirname}/`, ""),
streams: [{ stream: process.stdout, level: process.env.HEROKU_SLUG_COMMIT ? "info" : "debug" }, loggingBunyan.stream("debug")],
})
}
__filename
を与えることを想定しています。 main.ts
import { getLogger } from "./logger"
const logger = getLogger(__filename)
const main = async () => {
logger.debug("ロガー")
}
Generated from
GCP 外のアプリケーションのログを Stackdriver Logging で集める