how to import packages and some custom setting professionally in python? - python

I'm using logging packages with some custom setting and I have multiple directory, sub-directory and file So I'm coping and pasting logging setting in every file, this seems unprofessional. like
I'm doing in every file:
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S')
I want to put this in thing like utils.py file So I only import function from utils and start work.
What I try to do, file-name: utils.py
def logger():
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
Importing in some other file and seem it's not working,file-name: database_service.py
from src.utils import logger as logging
def connection_creator():
try:
client = MongoClient(DB_MACHINE, DB_PORT, serverSelectionTimeoutMS=2000)
status = client.server_info()['ok']
logging.info(f'Connection created Successfully! ["Status":{status}] `localhost` Port: `27017`')
db_connection = client['techexpert']
return db_connection
except Exception as error:
logging.error(f'in Creating connection `localhost` Port: `27017`! {error}')
db_connection = connection_creator()
Here logging.info() in unresolved reference So what could be best professional way to import these type of settings.

Related

Prevent Generation of Log File with Python logging

I have a simple script that I run as an exe file on Windows. However, when I am developing the script, I run it from the command line and use the logging module to output debug info to a log file. I would like to turn off the generation of the log file for my production code. How would I go about doing that?
This is the logging config I have setup now:
import logging
...
logging.basicConfig(filename='file.log',
filemode="w",
level=logging.DEBUG,
format="%(asctime)s: %(name)s - %(levelname)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
)
...
logging.debug("Debug message")
If you don't mind the generation of an empty log file for production, you can simply increase the threshold of logging to a level above logging.DEBUG, such as logging.INFO, so that messages logged with logging.debug won't get output to the log file:
logging.basicConfig(filename='file.log', # creates an empty file.log
filemode="w",
level=logging.INFO,
format="%(asctime)s: %(name)s - %(levelname)s - %(message)s",
datefmt='%d-%b-%y %H:%M:%S',
)
logging.debug("Debug message") # nothing would happen
logging.info("FYI") # logs 'FYI'
If you don't want logging to function at all, an easy approach is to override logging with a Mock object:
import logging
from unittest.mock import Mock
environment = 'production'
if environment == 'production':
logging = Mock()
...
logging.basicConfig(...) # nothing would happen
logging.debug(...) # nothing would happen

Logging Python SMTPHandler into emails for CLI SMTP Server

The goal is to complete a Flask tutorial where it is used logging.handler.SMTPHandler to send logs to SMTP debugging server from Python.
The Python server is run under windows cli, open a new windows CLI as admin and run:
python -m smtpd -n -c DebuggingServer localhost:1025
To test it the following code should work:
import logging
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
smtpHandler = logging.handlers.SMTPHandler(
mailhost = ("localhost",8025),
fromaddr = "alerts#localhost",
toaddrs = "geo555#localhost",
subject = "alert!"
)
smtpHandler.setLevel(logging.DEBUG)
logger.debug("here is the test logging for u.")
Have tried so far and no message is appearing in the debuggingserver:
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-vii-error-handling
Does not send any output to debugging server.
How can I send an email using python logging's SMTPHandler and SSL is not explicitly using the debugging server and it did not work.
What can be a very simple example that can do this, otherwise using debugging to file which also works.
Cheers.
I think you missed to add the stmpHandler to the logger: logger.addHandler(smtpHandler)
Below is a full working code:
import logging
import logging.handlers
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
sender = "emailuser#localhost"
pwd = "pass123"
smtpHandler = logging.handlers.SMTPHandler(
mailhost=("localhost", 25),
fromaddr="noreply#example.com",
toaddrs="user#email.com",
subject="alert!",
credentials=(sender, pwd),
)
smtpHandler.setLevel(logging.DEBUG)
# add this line
logger.addHandler(smtpHandler)
logger.debug("here is the test logging for u.")

Python logging not recording debug messages

I have created a package and I'm adding logging file to log debug information, here is my __init__.py file:
import logging
logging.basicConfig(filename='logs/tmp.log',
format='%(levelname)s %(asctime)s :: %(message)s',
level=logging.DEBUG)
logger = logging.getLogger('logs/tmp.log')
logger.debug('First debug!')
When I ran the code, the file logs/tmp.log wasn't even created, so I created the file manually just in case logging needs the file to exists, but it's not working either, any ideas on what am I doing wrong?

How to do logging in python in an explicit file

I tried below code only to find that my logs are getting printed in console.
What mistake I am doing here?
import logging
logging.basicConfig(filename="logger.log",
format='%(asctime)s %(message)s',
filemode='w')
logger=logging.getLogger()
logger.setLevel(logging.INFO)
logger.info("An information")
I am running this code as a fastapi project via uvicorn server.
Pass the log level to run method
uvicorn.run("example:app", host='localhost', port=8000, reload=True, log_level='info')
Use logger
from uvicorn.config import logger
logger.info('Your Comment')

Try to write into syslog

I am working in linux and the process rsyslogd is listening to port 514.
The following code can't write into /var/log/syslog.
Is anybody know what is the problem?
import logging
import logging.handlers
root_logger = logging.getLogger()
root_logger.setLevel(config.get_value("log_level"))
syslog_hdlr = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON)
syslog_hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
syslog_hdlr.setFormatter(formatter)
root_logger.addHandler(syslog_hdlr)
logger = logging.getLogger("imapcd.daemon")
logger.debug('test')
This code works fine in my system if I make some changes:
import logging.handlers as sh
syslog_hdlr = sh.SysLogHandler(address='/dev/log', facility=sh.SysLogHandler.LOG_DAEMON)
and
root_logger.setLevel(logging.DEBUG)
So check the logging level you are getting from config is not more restrictive than DEBUG (ex: if it is set to INFO no debug messages are printed).
If you still don't see anything on syslog try to use the syslog module and see if you get anything from there:
import syslog
syslog.syslog(syslog.LOG_ERR, "MY MESSAGE")

Categories

Resources