Example code in std.logger.core doesn't even work

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jul 13 06:25:23 UTC 2023


On Wednesday, July 12, 2023 11:13:52 PM MDT Danilo via Digitalmars-d wrote:
> Nice explanation. Thanks, Jonathan M Davis!
>
> After reading https://dlang.org/phobos/std_logger.html
> very exactly, we understand that `sharedLog` is the default
> internal logger. `sharedLog` can be used to change the default
> logger:
> ```d
>      //auto file = File("logFile.log", "w");
>      auto file = stderr; // stdout
>
>      sharedLog = cast(shared)new FileLogger(file);
> ```
> After that, `sharedLog` is not used directly (maybe the docs
> could make this more clear).
>
> Instead, we use:
> - log / logf
> - trace
> - info
> - warning / warningf
> - critical
> - error / errorf
> - fatal
>
> Those functions use `sharedLog` internally.
>
> If you look at the implementations, the provided default `Logger`
> and `FileLogger` are thread-safe already.
> They use mutexes to manage access to the global logger.
>
> So the correct way is to use the global functions or create
> local loggers using `auto logger = new WhateverLogger():
> logger.info("msg");`
>
> A complete example using threads was already provided at:
> -
> https://forum.dlang.org/post/lhewpbfniwozsqdvsudc@forum.dlang.org

Ah, so it uses free functions to handle the locking for sharedLog rather
than having shared member functions. I looked over the code quickly and saw
that it didn't have any shared member functions and concluded that it must
have left the locking issues up to the user. Clearly, I didn't look closely
enough.

My gut reaction to that is that maybe sharedLog should have had a setter
rather than being made public, but either way, since it's shared, no one is
going to accidentally do anything that isn't thread-safe to it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list