Hi.
I've created a pythontoolbox which consists of several scripts, each in it's own python-file. The toolbox works fine, and now I'm going to implement some logging. I've tried using the standard python module logging, but I'm not getting the results I'm expecting. Some times the logging works fine within the pythontoolbox, and other times nothing gets written to the logfile. If I restart ArcGIS Pro when the logging works, it stops working.
Does anyone have experience in using the logging-module? What is the best practice for using the logging module while working with pythontoolboxes?
I've also tried using just the logging.basicConfig. Using basicConfig works, but if there are any other pythontoolboxes also using basicConfig, everything gets written the same logfile even if filename in the basicConfig is different in the pythontoolboxes.
This is from my pyt, where I've created a new logger:
import logging
from CreateProjectTool import CreateProject
class Toolbox(object):
def __init__(self):
self.label = "Geoveg Toolbox"
self.alias = ""
handler = logging.FileHandler(filename='/temp/Geoveg.log')
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
self.tools = [CreateProject] In my other script (module), I have this code:
import logging
import traceback
import os
import sys
import zipfile
import arcpy
from pathlib import Path
logger = logging.getLogger(__name__)
class OpprettProsjekt(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Create new project"
self.description = ""
self.canRunInBackground = False
def getParameterInfo(self):
"""Define parameter definitions"""
workfolder = arcpy.Parameter(
displayName="Workfolder",
name="workfolder",
datatype="DEFolder",
parameterType="Required",
direction="Input")
params = [workfolder]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
return
def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
def execute(self, parameters, messages):
"""The source code of the tool."""
destinationFolder = "Geoveg"
folder = parameters[0].valueAsText
workfolder = os.path.join(folder, destinationFolder)
geovegTemplate = os.path.join(os.path.dirname(__file__), "Template")
try:
if os.path.exists(workfolder):
arcpy.AddMessage("Workfolder already exists")
logger.warning("Workfolder already exists.")
return
else:
# pakker ut innholdet i zip-filen med geoveg-mal
with zipfile.ZipFile(file=os.path.join(geovegMal, "Vegdata.zip"), mode='r') as archive:
archive.extractall(path=arbeidsMappe)
arcpy.AddMessage("Zip-file extracted at {0}".format(workfolder))
logger.info("Zip-file extracted at {0}".format(workfolder))
except:
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Concatenate information together concerning the error into a message string
pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
# Return Python error messages for use in script tool or Python window
arcpy.AddError(pymsg)
arcpy.AddError(msgs)
# Print Python error messages for use in Python / Python window
logger.error(pymsg)
logger.error(msgs)
return
def postExecute(self, parameters):
"""This method takes place after outputs are processed and
added to the display."""
return