Skip to content Skip to sidebar Skip to footer

How To Had Try Exception To Log To Logger Using Python

I have a Scenario where i want to check file exist at path or not But if file not exist at path catch the error and log it to file using logging module and then script should break

Solution 1:

I have modified your script and it's working

import os
import logging
import sys

logging.basicConfig(filename='log.txt',level=logging.INFO,format='%(asctime)s- %(message)s',filemode='a')

defcheckfileexist(Pth,Fle):
    var=Pth+'/'+Fle
    try :
        if (var isNone):
            logging.error('Path is empty')
            raise Exception("empty path")
        if os.path.exists(var):
            logging.error('File  found')
            return (var)
        else:
            raise Exception("File Not found")
    except Exception as e:
        logging.error('Not Found file')
        sys.exit()

   
defadditionvalue(a,b):
    return (a+b)
  • you were not logging the message %(asctime)s- %(message)s as well as instead of 'w' you should use 'a' (append)

Solution 2:

You can do it without raising any error:

defcheckfileexist(Pth,Fle):
    var = Path(Pth+'/'+Fle)
    if var.is_file():
        logging.info('File  found')
        return var
    else:
        logging.error('Not Found file')

But if you insist, you can do something like this:

defcheckfileexist(Pth,Fle):
    var = Path(Pth+'/'+Fle)
    try:
        ifnot var.is_file():
            raise FileNotFoundError()
 
    except FileNotFoundError as er:
        logging.error('Not Found file')

    else:
        logging.info('File  found')
        return var

need to check both the parameter is passed to the function checkfilexist()

When you define a function with required parameters (as the function above), Python will already raise an error if you don't pass all its parameters:

checkfileexist()
# Raises TypeError: checkfileexist() missing 2 required positional arguments: 'Pth' and 'Fle'checkfileexist('/c/d/',)
# Raises TypeError: checkfileexist() missing 1 required positional argument: 'Fle'

For the third case (raise an error if any argument is empty), you can do something like this:

defcheckfileexist(Pth,Fle):
    # Same as `if len(Pth) == 0:`ifnot Pth:
        raise TypeError("parameter Pth must not be empty")

    # Same as `if len(Fle) == 0:`ifnot Fle:
        raise TypeError("parameter Fle must not be empty")

    # ...

Solution 3:

After all above answers and tried on my editor and prepared this below script

Correct me if any thing wrong in below code

Thanks for helping me with your approach: @lakshika-parihar @enzo & @Joaquim Procopio

But this worked for me

import os
import logging
import sys

logging.basicConfig(filename='C:\\Users\\admin\\Desktop\\JUL\\log.txt', level=logging.INFO,
                    format='%(asctime)s : %(message)s', filemode='w')

defcheckfileexist(file_path, file_name):
    try:
        var_pth = str(file_path)
        var_fle = str(file_name)
        var_full = var_pth + var_fle

        if var_pth isNoneor var_pth == '':
            logging.error("Path parameter is empty")
            raise TypeError('Path parameter is empty')
        else:
            pass
            logging.info(f'Path : {var_pth}')

        if var_fle isnotNoneand var_fle != '':
            pass
            logging.info(f'Full : {var_fle}')
        else:
            logging.error("File parameter is empty")
            raise TypeError('File parameter is empty')

        if os.path.exists(var_full):
            logging.error(f'File : {var_fle} is found at path : {var_pth} ')
            logging.info(f'File : {var_full}')
            return var_full

    except:
        logging.error(f"ERRO : {erron} ")
        sys.exit()

try:
    #  Calling function#  checkfileexist('C:\\Users\\admin\\Desktop\\JUL\\', 'ABX')#  checkfileexist('', 'ABX')   #Output : 2021-07-28 22:45:48,307 : Path parameter is empty#  checkfileexist('', '')      #Output : 2021-07-28 22:46:53,758 : Path parameter is empty
    checkfileexist()               #2021-07-29 11:12:46,207 : ERROR : checkfileexist() missing 2 required positional arguments: 'file_path' and 'file_name'except Exception as er:
    logging.error(f"ERROR : {er} ")
    sys.exit()

Post a Comment for "How To Had Try Exception To Log To Logger Using Python"