LoginSignup
0
0

More than 3 years have passed since last update.

【Go】ビットフラグについて

Last updated at Posted at 2020-09-05

※注意: この記事ははあくまで個人学習用に整理しただけの記事で、内容としては不完全なものになります。読んでも参考にならない可能性が高いです。

go のサンプルコードを見ていたら以下のようなコードがあった

logger = log.New(file, "INFO ", log.Ldate|log.Ltime|log.Lshortfile)

上記の | (記号の名称: 日本語だとパイプまたはパイプライン、英語だと vertical bar)の部分が見慣れなかったので、最初は TypeScript の Union Types みたいな物かなと思ったが、調べてみたら、ビット演算子(bitwise operator)で、ビット論理和 (OR) だった。

普段 JavaScript を書いていて、ビット演算が使用されているコードはたまに見かけることがあったが、自分が書く事はほぼ無く、なぜここでビット論理和をしているのか理解できなかった。

調べたところ、どうやらビットフラグというフラグ制御方法があるらしい。ビットフラグの詳しい説明については以下がわかりやすかった。
C#で列挙型(enum)をビットフラグとして判定および演算する

log/log.go のソースコードには以下のようにコメントがある。

// These flags define which text to prefix to each log entry generated by the Logger.
// Bits are or'ed together to control what's printed.
// There is no control over the order they appear (the order listed
// here) or the format they present (as described in the comments).
// The prefix is followed by a colon only when Llongfile or Lshortfile
// is specified.
// For example, flags Ldate | Ltime (or LstdFlags) produce,
//  2009/01/23 01:23:23 message
// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
//  2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
const (
    Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
    Ltime                         // the time in the local time zone: 01:23:23
    Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
    Llongfile                     // full file name and line number: /a/b/c/d.go:23
    Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
    LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
    LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

上記のコメントを和訳する。

これらのフラグは、ロガーによって生成された各ログ エントリに接頭辞を付けるテキストを定義します。
ビットは、印刷される内容を制御するために一緒に並べられます。
出てくる順番(ここに記載されている順番)や、提示される形式(コメントに記載されている通り)をコントロールすることはできません。
Llongfile または Lshortfile が指定された場合のみ、接頭辞の後にコロンが続きます。
例えば、フラグLdate|Ltime(またはLstdFlags)は 2009/01/23 01:23:23 message を生成し、フラグ Ldate | Ltime | Lmicroseconds | Llongfile は 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message を生成します。

なるほど。ログとして出力する日時やファイル名などの付加情報のどれをログとして表示させるかをビットフラグという仕組みで設定することができるようだ。

非常に勉強になった。

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