LoginSignup
2
0

More than 3 years have passed since last update.

ログの置換出力あれこれ

Last updated at Posted at 2019-12-17

はじめに

会社的にPHPの話題が多い中、自分は.netの仕事をしているのですが、
先日そのプロジェクトで扱った話を。

ロガーで置換出力したい

その時は「個人情報に相当する文字列をマスキングして出力したい!」という要件だったのですが、
「ロガーにより出力される文字列を正規表現置換して出したい」という、よく有るのか無いのかわからない要件に対応した記録です。

NLogで置換出力

業務で扱っているプロジェクトにおいて、ロガーにNLogを使っていました。
configに追記すれば当該機能を利用できることがわかりました。

一般的な出力形式はtargetに以下のように書くと思います。


    <target xsi:type="File" name="file" fileName="${var:rootdir}/../var/log/app/${shortdate}.json">
      <layout xsi:type="JsonLayout">
        <attribute name="time" layout="${longdate}" />
        <attribute name="level" layout="${uppercase:${level}}" />
        <attribute name="eventid" layout="${event-properties:item=EventId.Id}" />
        <attribute name="logger" layout="${logger}" />
        <attribute name="message" layout="${message}" />
        <attribute name="url" layout="${aspnet-request-url}" />
        <attribute name="action" layout="${aspnet-mvc-action}" />
        <attribute name="exception" layout="${exception:format=tostring}" />
      </layout>
    </target>

この記述の前に以下のように定義を追加し


<variable name="replace_message" value="${replace:searchFor="正規表現":replaceWith="置換文字列":regex=true:inner=${message}}" />

もとの記述を

<attribute name="message" layout="${message}" /><attribute name="message" layout="${replace_message}" />

としてやればOK。
最初、ロガーの実装を弄ったり面倒なことになるかと思いましたが、
ちゃんと機能が用意されていて助かりました。

参考:https://github.com/NLog/NLog/wiki/Replace-Layout-Renderer

node.jsのconsole.logで置換出力

当該プロジェクトではnodejsの実装もあり、console.logにおいても同様に置換出力しなくてはなりませんでした。
そんなことできるのかと思いきや、よくよく考えたらこれも大したことなく実現可能でした。


const orglog = console.log;
console.log = (log) => {
  if (!log) {
    orglog(log);
    return;
  }
  log = {置換処理};
  orglog(log);
}

JSのこういう柔軟さは良くも悪くもゾクっとしますね。

2
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
2
0