Serenity Logger
A very fast and effiecient logging library. This library currently can log to files, rotate files when logging, log to the terminal, and is aware if the terminal is being piped during logging.
serenity::targets::FileTarget Class Reference

This class is in charge of logging to any basic file type and inherits from the TargetBase class for common logging functions and logging settings. More...

+ Inheritance diagram for serenity::targets::FileTarget:

Public Member Functions

 FileTarget ()
 Default constructor that sets the logger name to "File_Target" and sets all other values to their defaults.
 
 FileTarget (std::string_view fileName, bool replaceIfExists=false)
 Constructor that will set the file name and will truncate the file if it already exists and if "replaceIfExists" is set to true. Sets all other values to their defaults. More...
 
 FileTarget (std::string_view name, std::string_view filePath, bool replaceIfExists=false)
 Constructor that will set the logger name, file path, log directory, and whether or not to truncate this file if it exists or not. Sets all other values to their defaults. More...
 
 FileTarget (std::string_view name, std::string_view formatPattern, std::string_view filePath, bool replaceIfExists=false)
 Constructor that will set the logger name, format pattern to use, file path, log directory, and whether or not to truncate this file if it exists or not. Sets all other values to their defaults. More...
 
 FileTarget (const FileTarget &)=delete
 
FileTargetoperator= (const FileTarget &)=delete
 
 ~FileTarget ()
 Cleans up any background threads, flushes contents to disk, and closes the file context being used. More...
 
const std::string FilePath ()
 Returns the file path of the file context currently being held.
 
const std::string FileName ()
 Returns the file name of the file context currently being held.
 
void EraseContents ()
 Closes the file context currently being held and re-opens the same file context, truncating the file size to 0.
 
virtual bool RenameFile (std::string_view newFileName)
 Closes the file (if open) and trys to rename current file context. If rename is succesful, will re-open file context under the new file name. More...
 
bool OpenFile (bool truncate=false)
 Opens the file held by the file handle. More...
 
bool CloseFile ()
 Joins any currently running flush background thread (if enabled) and if the file handle's file context is currently open, will flush contents to disk and close the file. More...
 
void Flush ()
 If contents were written to buffer, this will now write contents of buffer to file and flush contents to disk, otherwise, just flushes contents to disk.
 
void SetFlushPolicy (serenity::experimental::Flush_Policy pPolicy)
 Sets the current policy in use to defer to the policy passed in from "pPolicy". More...
 
serenity::experimental::Flush_PolicyPolicy ()
 Returns the current policy in use.
 
const std::string LoggerName ()
 Returns the logger's name.
 
void SetPattern (std::string_view pattern)
 Calls the handle to the Message_Formatter's SetPattern( ) function. More...
 
void ResetPatternToDefault ()
 Resets the current format pattern in use to the default format pattern.
 
void SetLogLevel (LoggerLevel level)
 Sets the log level that messages should be logged at. More...
 
void WriteToBaseBuffer (bool fmtToBuf=true)
 Enables/Disables writing to a buffer. More...
 
bool isWriteToBuf ()
 Returns true if buffer writes are enabled and false if they are disabled.
 
std::string * Buffer ()
 Returns a pointer to the buffer container.
 
const LoggerLevel Level ()
 Returns the current log level setting (the threshold of whether to log a message or not).
 
void SetLoggerName (std::string_view name)
 Sets the name of the logger. More...
 
template<typename... Args>
void Trace (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::trace setting. More...
 
template<typename... Args>
void Info (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::info setting. More...
 
template<typename... Args>
void Debug (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::debug setting. More...
 
template<typename... Args>
void Warn (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::warning setting. More...
 
template<typename... Args>
void Error (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::error setting. More...
 
template<typename... Args>
void Fatal (std::string_view msg, Args &&...args)
 Logs a message giving the message a LoggerLevel::fatal setting. More...
 

Protected Member Functions

void PolicyFlushOn () override
 Executes the currently set flush policy. More...
 
void PrintMessage (std::string_view formatted) override
 Writes the message passed in by the formatted variable to the file context. More...
 
msg_details::Message_FormatterMsgFmt ()
 Returns a pointer to the handle for the Message_Formatter class instance.
 
msg_details::Message_InfoMsgInfo ()
 Returns a pointer to the handle for the Message_Info class instance.
 

Protected Attributes

std::ofstream fileHandle
 Protected file handle that holds the file context. More...
 
FileSettings fileOptions
 The structure this class and the derived class ( RotatingTarget ) use to keep track of basic file settings. More...
 
BackgroundThread flushWorker
 The structure this class and the derived class ( RotatingTarget ) use to flush contents to disk on an interval basis. More...
 

Detailed Description

For all FileTarget Constructors:

  • If either the directories or the file don't exist yet, the constructor will create the neccessary
    directories as well as the file needed to write to.
  • Default initializes the TargetBase inherited values
    • These being the flush policy, the log level, and time mode.
    • For the constructors that don't take in a format pattern, this also includes the default pattern

      For the constructors that don't take a file path argument:
  • The log directory and log itself is created in the location that the application being run is located.
  • The default log directory is named "Logs".
  • The default file name is "Generic_Log.txt" and will be created under the default log directory.

Constructor & Destructor Documentation

◆ FileTarget() [1/3]

serenity::targets::FileTarget::FileTarget ( std::string_view  fileName,
bool  replaceIfExists = false 
)
explicit

While the file name will be changed to the parameter fileName, the file itself will be created under the default log directory.

Parameters
fileNameThe name of the file to create and/or use for logging
replaceIfExistsThis value denotes whether or not to truncate the file if it exists already

◆ FileTarget() [2/3]

serenity::targets::FileTarget::FileTarget ( std::string_view  name,
std::string_view  filePath,
bool  replaceIfExists = false 
)
explicit

The name of the logger will be set based on the name variable. The file path should include the log directory and the actual file name in the filePath variable as this is how it's intended to be parsed. If the file already exists and the replaceIFExists variable is set to true, then the file will be truncated before opening for use in logging

Parameters
nameThe name the logger will be identified by.
filePaththe full path to the file. This value should include any directories as well as the file name itself.
replaceIfExistsThis value denotes whether or not to truncate the file if it exists already

◆ FileTarget() [3/3]

serenity::targets::FileTarget::FileTarget ( std::string_view  name,
std::string_view  formatPattern,
std::string_view  filePath,
bool  replaceIfExists = false 
)
explicit

The name of the logger will be set based on the name variable. The format pattern used can be empty if no prepended text is wanted and can include any of, none of, or all of the flags if desired. The file path should include the log directory and the actual file name in the filePath variable as this is how it's intended to be parsed. If the file already exists and the replaceIFExists variable is set to true, then the file will be truncated before opening for use in logging

Parameters
nameThe name the logger will be identified by.
formatPatternThe pattern that is used to determine how the prepended text is displayed before the log message.
filePathThe full path to the file. This value should include any directories as well as the file name itself.
replaceIfExistsThis value denotes whether or not to truncate the file if it exists already

◆ ~FileTarget()

serenity::targets::FileTarget::~FileTarget ( )

Cleans up background flush thread if enabled by joining the thread and then flushing the contents of the file handle to the file (if messages were written to buffer, will now write contents of buffer to file). Afterwards, the file context being used is closed.

Member Function Documentation

◆ CloseFile()

bool serenity::targets::FileTarget::CloseFile ( )
Returns
If successful, returns true. If unsuccessful, will return false with error message

◆ Debug()

template<typename... Args>
serenity::targets::TargetBase::Debug ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ Error()

template<typename... Args>
serenity::targets::TargetBase::Error ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ Fatal()

template<typename... Args>
serenity::targets::TargetBase::Fatal ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ Info()

template<typename... Args>
serenity::targets::TargetBase::Info ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ OpenFile()

bool serenity::targets::FileTarget::OpenFile ( bool  truncate = false)

Opens the file context currently being held and sets the file buffer size using "DEFAULT_BUFFER_SIZE" macro. If the file doessn't already exist, this function will create the file first.

Returns
If successful, returns true. If unsuccessful, will return false with error message

◆ PolicyFlushOn()

void serenity::targets::FileTarget::PolicyFlushOn ( )
overrideprotectedvirtual

Compares current flush setting and executes that policy if active. Current policies are: always flush, never flush, LogLevel-based flushing and time-based flushing. Time based flushing uses a background thread worker which will intermittenly lock the file when elapsed time is reached from "flushEvery" setting, flush the contents to disk, and then unlock the file for further writes

Reimplemented from serenity::targets::TargetBase.

◆ PrintMessage()

void serenity::targets::FileTarget::PrintMessage ( std::string_view  formatted)
overrideprotectedvirtual

Checks if background flush thread is active, if it is - will lock access to the file for writing. If rotate setting is enabled, will check that the file size doesn't exceed file size limit and writes the message to the file. If the file size would exceed the limit, closes the current file and rotates to next file before writing the message. Will then follow any settings active in the flush policy

Parameters
formattedThe actual message in its entirety to send to the output destination.

Implements serenity::targets::TargetBase.

Reimplemented in serenity::experimental::targets::RotatingTarget.

◆ RenameFile()

bool serenity::targets::FileTarget::RenameFile ( std::string_view  newFileName)
virtual

Virtual function that can be overriden in derived classes. The intended usage is to close the file, try to rename the current file, and then open the file again. This implementation trys to catch any errors in the renaming process and opening process by returning an error message.

Attention
This function, while it doesn't neccessarily throw, does not handle any exceptions that may be thrown when executed. It simply returns an error message to help diagnose issues; error handling is expected to be implemented by the user in this case.
Returns
If successful, returns true. If unsuccessful, will return false with error message

Reimplemented in serenity::experimental::targets::RotatingTarget.

◆ SetFlushPolicy()

void serenity::targets::TargetBase::SetFlushPolicy ( serenity::experimental::Flush_Policy  pPolicy)
inherited
Parameters
pPolicyrefers to any settings that are added or changed by the user, including whether to flush always, never, or periodically.

On top of having options to never flush, always flush, and periodically flush, the Flush_Policy class includes the settings for whether flushing should occur based on a time-interval or log level if the periodical flushing option is enabled.

◆ SetLoggerName()

void serenity::targets::TargetBase::SetLoggerName ( std::string_view  name)
inherited
Parameters
namethe name that the logger itself will use and be identified by

◆ SetLogLevel()

void serenity::targets::TargetBase::SetLogLevel ( LoggerLevel  level)
inherited

For example, if "SetLogLevel(LoggerLevel::Error);" is used, then no messages below LoggerLevel::Error will be logged, however once a Fatal or Error message is made, then they would be logged to the output destination

Parameters
level- the logger level threshold that will determine if a message should be logged or not

◆ SetPattern()

void serenity::targets::TargetBase::SetPattern ( std::string_view  pattern)
inherited

Sets the format pattern variable and parses the format string for internal storage and usage of this pattern by initializing and moving the initialized formatter struct in charge of the respective flag to a Formatters container

Parameters
pattern- the format pattern to store. This pattern is what determines how the prepended text will be displayed before the log message

◆ Trace()

template<typename... Args>
serenity::targets::TargetBase::Trace ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ Warn()

template<typename... Args>
serenity::targets::TargetBase::Warn ( std::string_view  msg,
Args &&...  args 
)
inherited

Checks if the message should be logged via the log level threshold setting. If it isn't, immediately returns. If the message should be logged, this function will then perform a quick check on whether or not writes to the buffer were enabled and will write to the buffer if they were. If writes to the buffers weren't enabled, then PrintMessage( ) will be called and the derived target handles how this is implemented. After writing the message, follows the derived target's PolicyFlushOn( ) implementation

Template Parameters
msgThe message being passed in. Follows C++20's format library and libfmt's substitution model using "{}" to replace any arguments from the args parameter.
argsVariadic placeholder for any number of and any type of arguments to use in substituion.

◆ WriteToBaseBuffer()

void serenity::targets::TargetBase::WriteToBaseBuffer ( bool  fmtToBuf = true)
inherited

When writing to the buffer, messages will be appended with the platform-specific end of line before being added to the buffer. When Flush( ) is called, if writing to the buffer was enabled, the buffer contents will now be written to the file and then flushed to disk. Disabled by default.

Parameters
fmtToBufthe value that controls whether or not buffer writes are enabled/disabled

Member Data Documentation

◆ fileHandle

serenity::targets::FileTarget::fileHandle
protected

This variable is protected to avoid duplication if using RotatingTarget class due to it inheriting from this class.

◆ fileOptions

serenity::targets::FileTarget::fileOptions
protected
See also
FileSettings

◆ flushWorker

serenity::targets::FileTarget::flushWorker
protected

The documentation for this class was generated from the following files: