EnLogger는 디버그 콘솔이나 특정 출력 시스템에 제한되지 않고 사용자 정의 로그 메시지를 작성할 수 있도록 해주는 플러터 애플리케이션용 유연한 로깅 패키지입니다. 안드로이드, iOS, 웹, macOS, 윈도우, 리눅스 등 다양한 플랫폼을 지원하며, 어떤 프로젝트에도 원활하게 통합할 수 있습니다. 확장 가능한 설계 덕분에 사용자는 자신만의 로그 핸들러와 포맷을 정의할 수 있어 디버깅, 모니터링, 분석에 이상적입니다. 이 패키지는 단순성과 제어력을 강조하여 개발자가 자신의 정확한 필요에 맞게 로깅 동작을 조정할 수 있도록 합니다.
사용 사례
응용 프로그램 흐름 디버깅
런타임 동작 모니터링
사용자 정의 로그 출력 라우팅
외부 분석 도구와의 통합
오류 시나리오 테스트
생산 환경에서 로그인하기
주요 기능
확장 가능한 로그 핸들러 시스템
다중 플랫폼 지원
사용자 정의 로그 형식
디버그 콘솔에 의존하지 않음
기존 코드와의 간편한 통합
유연한 출력 대상
적합한 대상
사용자 지정 로깅이 필요한 개발자
크로스 플랫폼 앱을 개발하는 팀
구조화된 로그가 필요한 프로젝트
복잡한 디버깅 요구 사항을 가진 애플리케이션
로깅이 포함된 프로덕션 대상 앱
하드코딩된 콘솔 출력을 피하는 사용자
고려 사항
로그 핸들러의 수동 설정이 필요합니다
내장된 로그 저장 또는 지속성 없음
고급 사용 사례를 위해 추가 구성이 필요할 수 있습니다
고주파 로깅에 최적화되지 않음
완전한 로깅 프레임워크와 비교해보면 기본 기능이 제한적이다
사용자 정의 로직에 따라 메시지 처리가 달라집니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
En Logger
Welcome to EnLogger—a highly flexible and extensible logging system designed to adapt to your application's unique needs.
Instead of restricting you to the standard debug console, EnLogger acts as a central hub. It broadcasts your log messages to a customizable list of EnLoggerHandlers. You simply log your message once, and let your attached handlers decide where and how that data is processed.
Key Features:
Plug-and-Play Architecture:Log once, write anywhere. You can easily implement custom handlers based on your specific requirements:
Need local persistence? Implement a handler that writes logs to a local file.
Need remote crash reporting? Create a handler that pipes messages directly to Sentry, Crashlytics, or Datadog.
Lazy Evaluation: Boost your app's performance with "lazy" logging. Wrap expensive string interpolations or data serializations in closures; if the log level is disabled, the computation is completely skipped (see the Lazy messages section for details).
Zone: Automatically extract contextual data (tags) from Zone.current and attach them to every log event.
Caller info Indicates the exact location in your source code where the log was emitted
Syslog Standards: All log operations strictly adhere to the standard syslog severity levels (Emergency, Alert, Critical, Error, Warning, Notice, Info, Debug).
Ready-to-use Console Logger: Get started immediately with the included DevLogHandler, which outputs beautifully colored and formatted messages straight to your developer console.
To see these features in action, check out the example project.
Messages can include attachments such as serialized data, file contents, and more.
// error with data
logger.error(
"error",
data: [
EnLoggerData(
name: "response",
content: jsonEncode("BE data"),
description: "serialized BE response",
),
],
);
Instances
To avoid having to rewrite the prefix each time, you can create instances based on EnLogger. For instance, if you have a specific scope (like the API repository), you can instantiate a EnLogger with the prefix "API repository," and this prefix will be included in every log unless you explicitly override it.
final instLogger = logger.getConfiguredInstance(prefix: 'API Repository');
instLogger.debug('a debug message'); // [API Repository] a debug message
instLogger.error(
'error',
prefix: 'Custom prefix',
); // [Custom prefix] a debug message
Lazy messages
Lazy messages are not evaluated until at least one handler is going to write them.
Use them to avoid expensive computations when a log level is disabled (e.g. in production, where debug is often turned off).
The message closure is only called when at least one handler returns true from can(severity) for that log.
logger.lazyDebug(() => 'a lazy debug message');
// The closure is not run if debug is disabled (every handler's `can` returns `false`)
By default, can returns true for every handler, so all log levels are written unless you override it.
The message callbacks (e.g. the closure passed to lazyDebug) may be asynchronous. Handle exceptions inside the callback, otherwise they are ignored.
Tags & Zones
EnLogger can automatically extract contextual data (tags) from Dart's [Zone.current] and attach them to every log event.
By providing zoneContextKeys to the constructor, the logger will capture only the specified keys from the current execution zone.
Additionally, every logging method accepts its own tags parameter. The handlers will receive a single, merged, and sanitized map containing both the requested zone tags and the method-specific tags.
final logger = EnLogger(
zoneContextKeys: {#userId},
...
);
runZoned(
() {
// In addition to the method tags, the zoneContextKeys // values will be extracted from the zones
logger
.debug('a debug message',
prefix: 'API Repository',
tags: {'custom_key':'custom_value'},
);
},
zoneValues: {
#userId: 123,
#tenantId: 'abc'
},
);
Caller info
callerInfo captures the exact location in your source code where a log was emitted. It provides the function name, file path, and line number (e.g., AuthRepository.login (/lib/auth_repository.dart:142:5)).
While an error stackTrace shows you where an exception crashed, callerInfo pinpoints exactly where you wrote the log statement.
Because extracting stack traces is a CPU-intensive operation, this feature is disabled by default. You can explicitly enable it when initializing EnLogger:
final logger = EnLogger(includeCallerInfo: true);
Closing the logger
When you are done using an EnLogger instance, you should clean up its resources. EnLogger provides a graceful shutdown mechanism that safely stops accepting new logs and waits for any pending asynchronous writes or lazy evaluations to finish before clearing its handlers, ensuring no data is lost.
You can trigger this shutdown using two methods depending on your architectural needs:
close(): The preferred, asynchronous method. You can await it to guarantee all pending logs have been fully processed and written before proceeding.
dispose(): A synchronous wrapper around close(). It immediately marks the logger as closed and handles the graceful shutdown in the background (fire-and-forget).
Note: Both methods are safe to call multiple times (idempotent) and automatically cascade the shutdown to any child instances created via getConfiguredInstance().
Override can method to filter logs to complete skip the log evaluation.
@overrideboolcan({requiredSeverity severity, String? prefix}) {
if (isProduction) {
return severity.atLeastError; // only error and above are evaluated and written
}
returntrue; // every log is evaluated and written (default behavior)
}