LoginSignup
3
0

More than 5 years have passed since last update.

開発時にのみlogを表示したい

Posted at

bool.fromEnvironmentおよび--defineを使用する。

設定

const bool isReleaseMode =
    const bool.fromEnvironment('releaseMode');

pub serveによる開発時、およびデバッグビルド時はリリースモードは適用されない。

pub serve
pub build --mode=debug

リリースビルド時のみこのオプションを適用する。

pub build --mode=relese --define releaseMode=true

Logger

あとはこのようにloggerを作ってやればよい。

bool get isDebugMode => !isReleaseMode;

final Logger _logger = new Logger('CLIENT: ', isDebugMode);

class Logger {
  final logging.Logger _logger;

  factory Logger(String name, isDebugMode) {
    logging.Logger.root.level =
        isDebugMode ? logging.Level.ALL : logging.Level.WARNING;

    logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
      print('${rec.level.name}: ${rec.time}: ${rec.message}');
    });
    return new Logger._(new logging.Logger(name));
  }
  Logger._(this._logger) {
    debug('Logger is enabled in debug mode.');
  }

  /// Use it for logging a debug message.
  void debug(message, [Object error, StackTrace stackTrace]) {
    _logger.fine(message, error, stackTrace);
  }
}

明示的にオプションを追加しないとデバッグログが流れないようにしたかったが、pub serveには--defineオプションが無いので、リリースビルド時にのみこのフラグを追加する運用とした。

やらないほうがいい方法

bool isDebugMode() {
  try {
    assert(false);
  } on AssertionError catch(_) {
    return true;
  }
  return false;
}

このようなassertionのなかばexploitな方法は迂遠な上にbuild方法によっては--checkedオプションや--enable-assertオプション(https://github.com/dart-lang/sdk/commit/3b05eb95530b1684a3fbcc69bda1784db393b966) と組み合わせて運用する必要が出てきて複雑になるのでできればやらないほうがよいと思う。
https://github.com/dart-lang/sdk/issues/29601

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