PowershellFrameworkCollective / psframework

A module that provides tools for other modules and scripts
MIT License
435 stars 41 forks source link

Does logging to a SQL provider flush log entries when it's process ends? #551

Closed ashdar closed 2 years ago

ashdar commented 2 years ago

Hello.

I'm not 100% sure if I'm reporting a bug or just asking a question.

If I run a task via Windows scheduler and the task ends, which closes out that Windows process, does PSFramework have enough time to persist whatever entries have been queued up to the SQL provider?

IOW, my scripts take the general form of something like this:

$Message = 'Script is just starting'
Write-PSFMessage -Message $Message -Level 'Verbose' -Tag 'Started'

#lots of stuff that takes several minutes, or maybe hours.

$Message = 'Script is all done'
Write-PSFMessage -Message $Message -Level 'Verbose' -Tag 'Completed'
# and now the script ends and the Windows Scheduler task finishes and Windows shuts down my process

Later, I have code/tests/checks that look for a log entry tagged with 'started' and a separate log entry tagged with 'Completed'. If my scheduled task runs once each day, I should see one 'started' entry and one 'completed' entry each day. If I don't see those entries in the log, I should suspect that my script didn't run correctly.

My issue is that, sometimes, I'm not seeing the 'Completed' log entries. Looking at what the script actually did, it seems like the script ran correctly and completed correctly.

Bearing in mind the asynchronous nature of how PSFMessage writes, is it possible that my process is getting shut down before PSFramework has a chance to gracefully shut down and persist that last 'Completed' log entry?

IOW, is Windows closing down my process before PSFramework gets a chance to gracefully close down?

If so, is this something that I could (or should) work around by having my script sleep for a few seconds before ending? Or is there some kind of "Flush-LoggingProvider" that I haven't spotted in the framework?

FriedrichWeinmann commented 2 years ago

Yeah, it was supposed to flush correctly and in most cases it actually does ... but in some it does not, which is a bad thing of course. To wait until all the logging has completed use:

Wait-PSFMessage

I have only recently figured out the why and how (mostly because it is not a problem in most cases) and forgot to update the docs on that one, sorry :(

ashdar commented 2 years ago

No worries. Thanks for the quick turn-around.

ashdar commented 2 years ago

I presume that I can just add that to a Finally{} block in my topmost Try/Catch. Is that right?

FriedrichWeinmann commented 2 years ago

Yupp, that would work.

ashdar commented 2 years ago

Just to close this issue out. I did add finally {Wait-PSFMessage} to my scripts and I am seeing my 100% of my completion messages now. Thanks!