-
-
Notifications
You must be signed in to change notification settings - Fork 6
6 Code tips and tricks
Here are some additional tips to help you write clean, efficient, and maintainable code for Logicytics, These include some already made custom libraries, some special GLOBAL variables and some special functions that can be used to make your life easier.
Tip
The file _MOD_SKELETON.py
describe the use cases as well, check it out!
For more professionals who can understand how the project wrapper actually works, you may utilise special mechanism's
To use Logs with its special settings, just modify the log = Log()
line of code with any of the following parameters in dictionary format:
from logicytics import *
if __name__ == "__main__":
log = Log({
"filename": "../ACCESS/LOGS/Logicytics.log", # Specifies the path to the log file.
"use_colorlog": True, # A Boolean indicating whether to use colored logging output - Keep it `True`.
"log_level": DEBUG, # Sets the logging level. Better leave it as the `DEBUG` variable.
"debug_color": "cyan", # Color for debug messages.
"info_color": "green", # Color for info messages.
"warning_color": "yellow", # Color for warning messages.
"error_color": "red", # Color for error messages.
"critical_color": "red", # Color for critical messages.
"exception_color": "red", # Color for exception messages.
"colorlog_fmt_parameters": "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", # Format string for colored log messages.
"truncate_message": True, # A Boolean indicating whether to implement/use truncation (~150) or not (raw message)
})
Always use the log
object to log messages, instead of using print()
directly.
Use the following format:
from logicytics import Log
if __name__ == "__main__":
log = Log()
Where Log()
is the default settings, you can change it to your liking - Using {"log_level": DEBUG}
etc.
If for some reason you need to log something, but cant hardcode the log type, and may use a string for that purpose, then use the following line:
from logicytics import Log
if __name__ == "__main__":
log = Log()
log.string("MESSAGE", "LOG_TYPE")
Replace MESSAGE
with the text to actually be logged
Replace LOG_TYPE
with the following available strings:
"INFO": log.info
"WARNING": log.warning
"ERROR": log.error
"CRITICAL": log.critical
Anything Else: log.debug
Tip
Its case insensitive, and understands minor shortcuts (like crit
for critical
!)
Caution
If the value LOG_TYPE
is incorrect, it gives a Internal
error message. Won't produce a crash though!
To create a new line on the log being generated, use the following code:
from logicytics import Log
if __name__ == "__main__":
log = Log()
log.newline()
Note
This can work with the above two features, and doesn't actually need DEBUG to be true, it creates a new line with separators for both the terminal AND log file,
Any function can use this new decorator, by using the following code:
from logicytics import Log
if __name__ == "__main__":
log = Log()
@log.function
def main()
pass # Place logic here
main()
When this is run, it logs the time it started and ended and outputs its speed/time taken in debug mode, this makes it very easy to debug code later, and find which segments need optimisation
An example of how it works can be seen in _MOD_SKELETON.py
Although this will fail and not work if you don't follow its proper initialisation:
- It requires
log
to be initialised properly - The function must be a main function, not a side-function - as in,
do_this
can use this decorator, while__do_this_part
shouldn't as it help's the functiondo_this
continue its work, aka don't use the decorators for helper functions. - It must be the last decorator, so if there is more than 1 decorator, the line order, it should be last (i.e it should execute the function first)
Example of a don't script:
# DONT: Used a wild import, this is not advised
from logicytics import *
# DONT: Failed to initialise log in the beginning of the script
class Main:
@log.function
@classmethod # The classmethod surpasses the log.function, this is not allowed, as then log.function doesn't get a callable method, this should switch order.
def main(cls):
return cls.__main_helper()
@staticmethod
@log.function # This is a side-function, it is intended to not execute by itself, so it shouldn't have the decorator
def __main_helper():
return "Example of helper"
main()
Tip
Do use this as it really will help in debugging and optimisation's in the long run.
Check out _MOD_SKELETON.py
to see the Do's in coding.
Many custom libraries are used to reduce redundancy - they are more of a local python file that is imported.
They are .py
files inside the module logicytics
(aka the directory CODE/logicytics
)
They hold very powerful and useful values, to learn more about their documentation,
Variable Name | Description |
---|---|
DEBUG | Value from config.ini - DEBUG on or off (bool) |
VERSION | The current version of the local project |
CURRENT_FILES | You may ignore this as they can't help you develop anything, its used by the debugger to check if your files are intact |
Note
These do not have the custom log.function
decorator, and so will not produce the debug logs for them
Only functions that are useful for development is shown here
Class.Method_Name | Description | Argument Use Case |
---|---|---|
Check.admin() | Checks if the current user has administrative privileges. | None |
Check.execution_policy() | Checks if PowerShell execution policy is set to unrestricted. | None |
Check.uac() | Checks if User Account Control (UAC) is enabled on the system. | None |
Check.sys_internal_zip() | Extracts the SysInternal_Suite zip file if it exists and is not ignored. | None (checks for files and extracts the zip if conditions are met). Raises an exception if an error occurs during the extraction process. |
Execute.script(script_path) | Executes a script file based on its extension. Handles Python and PowerShell scripts differently. |
script_path (str) : Path of the script to execute. .py scripts are run as Python scripts, .ps1 scripts are unblocked and executed, and others are processed for specific message parsing. |
Execute.command(command) | Runs a command in a subprocess and returns the output as a string. |
command (str) : Command to be executed. The method captures and returns the command's standard output. |
FileManagement.open_file(file, use_full_path) | Opens a specified file using its default application in a cross-platform manner. |
file (str) : Path of the file to open. use_full_path (bool) : If True , uses the full path; otherwise, resolves to the real path. |
FileManagement.mkdir() | Creates directories for logs, backups, and data storage. | None |
FileManagement.Zip.and_hash(path, name, flag) | Zips files, generates a SHA256 hash, and moves the files. |
path (str) : Directory containing files. name (str) : Base name for output files. flag (str) : Flag to include in the output file name. Returns a tuple with success messages or an error message. |
Get.list_of_files(directory, extensions, append_file_list, exclude_files) | Retrieves a list of files in the specified directory with the specified extensions. |
directory (str) : Path of the directory to search. extensions (tuple or bool) : Extensions to filter files or True for all files. append_file_list (list) : Existing list to append filenames. exclude_files (list) : The files to exclude from return |
Get.config_data() | Retrieves configuration data from the config.ini file. |
None. Returns a tuple: log_level (str) , version (str) , files (list[str]) , and delete_old_logs (bool) . |
Important
The Execute.script(script_path)
is finicky with it's return statements for logging, and so I advice using it as follows Log().parse_execution(Execute.script(script_path))
Tip
We have omitted the Logger.py
documentation as its from the repo AlgoPy,
check it out to understand more on the custom logging mechanism - Here is the direct documentation of the class Log.
This project has made minor modifications on it though, these minor modification can be found here.
Acknowledge your contributions appropriately in the CREDITS.md
file.
Use the following template when asked to add your contributions in the PR:
### File-Created/CONTRIBUTION by MAIN-Username
What you did, created, removed, refactored, fixed, or discovered.
- [Your GitHub Username](https://github.com/YourGitHubLink)
- [Your GitHub Username](https://github.com/YourGitHubLink) etc...
This ensures proper attribution and recognition for your efforts.
Tip
This is also found in the PR template!
By following these guidelines and practices, you can effectively contribute to open-source projects, enhancing both your skills and the broader community's knowledge and tools.
Wiki Last Updated on version 3.3.0
of Logicytics on day 02-01-2025
.