SourceHorizon / logger

Small, easy to use and extensible logger which prints beautiful logs.
https://pub.dev/packages/logger
MIT License
197 stars 33 forks source link

Async Init Methods in Constructor #61

Closed and-y closed 6 months ago

and-y commented 7 months ago

I've encountered an issue related to the initialization process within the Logger class, specifically around its constructor behavior when dealing with asynchronous initialization methods like LogOutput.init. In my use case, I've implemented a custom LogOutput that requires awaiting some resources in its init method. However, I've noticed that the output method of LogOutput gets invoked before the init method has had a chance to fully complete.

This behavior stems from the fact that asynchronous methods cannot be awaited directly within constructors in Dart. This presents a challenge for ensuring that all necessary asynchronous initialization is completed before the Logger instance starts invoking methods that depend on that initialization.

To address this issue, I propose the introduction of an asynchronous factory method. This method would perform the necessary await operations on the initialization calls and only resolve with an instance of the Logger class once all asynchronous setup is fully completed. This change would ensure that instances of Logger are fully initialized and ready to use, avoiding premature method calls that assume initialization has already occurred.

Bungeefan commented 6 months ago

Hi, sorry for the late response. Yeah, this is still a flaw I haven't been able to fix yet. Only recently has it become possible to await any async code in output's destroy() methods at all (like in FileOutput).

Anyway, I would like to propose a different solution, a getter that returns a future which is connected to all the init() futures. Then you would be able to optionally await this future after creating the logger:

await logger.init;