I am writing a python script to reconcile and post my user version edits to a QA/QC version and then finally to the SDE database, the script will also go further to compress, analyze and index the database. I need the script to output all events including errors encountered during execution to a log file in text format with date and time attached to the log filename.

So far the script is able to perform all the task but it does not write the events to the log, it just displays it in the console. I believe it is just one line of code that will be needed to get the script to write the events to the log file generated but unfortunately I have not been able to get this line correctly.

The script is pasted below

import arcpy
import sys
import os
import datetime
import traceback

# Database Connection
editDB = "Database Connections\\Frogmouth_Natural_Resources.sde" #Connect to the Natural Resources databse using TC_USer admin access"
# Current Day
Day = time.strftime("%m-%d-%Y", time.localtime())
# Current Time
Time = time.strftime("%I:%M:%S %p", time.localtime())

# Set workspace
workspace = editDB

# Set the workspace environment
arcpy.env.workspace = workspace
arcpy.env.overwriteOutput = True

    # Start Time
    print 'Process Started at ' + str(Day) + " " + str(Time)

 # block new connections to the working and Frogmouth database.
  #  print "Blocking Connections..."
  #  arcpy.AcceptConnections(editDB, False)

# disconnect all users from the working and Frogmouth database.
    #print "Disconnecting Users..."
    #arcpy.DisconnectUser(editDB, "ALL")

# Get a list of all child versions besides QAQC and DEFAULT to pass into the ReconcileVersions tool.
    ver1List = [ver1.name for ver1 in arcpy.da.ListVersions(editDB) if ver1.name != 'TC_USER.QA/QC' and ver1.name != 'sde.DEFAULT']

# Execute the ReconcileVersions tool with QAQC Target Version and do not delete child versions
    print "Reconcile/post versions to QAQC...."
    arcpy.ReconcileVersions_management(editDB, "ALL_VERSIONS", "TC_USER.QA/QC", ver1List, "LOCK_ACQUIRED", "ABORT_CONFLICTS", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST", "KEEP_VERSION")

# Extract QAQC version from the list of versions to pass to ReconcileVersions tool.
    ver2List = [ver2.name for ver2 in arcpy.da.ListVersions(editDB) if ver2.name == 'TC_USER.QA/QC']

# Execute the ReconcileVersions tool with DEFAULT Target Version and do not delete QAQC version
    print "Reconcile/post QAQC to DEFAULT..."
    arcpy.ReconcileVersions_management(editDB, "ALL_VERSIONS", "sde.DEFAULT", ver2List, "LOCK_ACQUIRED", "ABORT_CONFLICTS", "BY_OBJECT", "FAVOR_TARGET_VERSION", "POST", "KEEP_VERSION")

# Run the compress tool.
    print "Compressing database..."

# /////////////////////////////////// ANALYZE DATASETS AND CALC STATISTICS /////////////////////////////////////

    # NOTE: Rebuild indexes can accept a Python list of datasets.

    # Get a list of all the datasets the user has access to.
    # First, get all the stand alone tables, feature classes and rasters.
    dataList = arcpy.ListTables() + arcpy.ListFeatureClasses() + arcpy.ListRasters()

# Next, for feature datasets get all of the datasets and featureclasses
    # from the list and add them to the master list.
    for dataset in arcpy.ListDatasets("*", "Feature"):
        arcpy.env.workspace = os.path.join(workspace, dataset)
        dataList += arcpy.ListFeatureClasses() + arcpy.ListDatasets()

        # reset the workspace
    arcpy.env.workspace = workspace

    # Concatenate all datasets into a list
    datasetList = [ds for ds in dataList]

    print "rebuilding indexes"
    # Execute rebuild indexes
    # Note: to use the "SYSTEM" option the workspace user must be an administrator.
    arcpy.RebuildIndexes_management(workspace, "NO_SYSTEM", datasetList, "ALL")
    print('Rebuild Complete')

    print "analyzing datasets"
    arcpy.AnalyzeDatasets_management(workspace, "NO_SYSTEM", datasetList, "ANALYZE_BASE", "ANALYZE_DELTA", "ANALYZE_ARCHIVE")
    print "analysis complete"

    #Allow the database to begin accepting connections again
    print "Set databases to allow connections..."
    arcpy.AcceptConnections(editDB, True)

    # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ script initiation, Rec/Post process error handling \\\\\\\\\\\\\\\\\\\\\\\\\\\\\

    print 'An error occured'
    failMsg += 'Most recent GP messages below.\n'
    failMsg += arcpy.GetMessages() +'\n'
    failMsg += '\nTraceback messages below.\n'
    failMsg += traceback.format_exc().splitlines()[-1]
    print failMsg
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ write error log info\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

# move to working directory 
    os.chdir (u'Y:\\TOOLS\\Logs\\')
## define function with variable filename and the format of the timestamp
    def timeStamped(filename, fmt='%m-%d-%y-%H.%M.%S-{filename}'):
       return datetime.datetime.now().strftime(fmt).format(filename=filename)
## assign local variable filename and use whatever file name and extension you need
    filename = timeStamped('Infrastructure_RecPost_toQC_Log.txt')
## Create the logfile and assign write permission
    file = open(filename, "w")
    for line in file:
        print line

## and do it again for the second file
    filename = timeStamped('Infrastructure_RecPost_toDefault_Log.txt')
## Create the logfile and assign wright permission
    open(filename, "w")
  • Welcome to GIS SE! As a new user please take the tour to learn about our focused Q&A format. I would recommend you create a test script of just a few lines and attempt to produce your output in that. Using your test script and results here would make it much easier for potential answerers to try what you're doing and read through your script. – Midavalo Jul 7 '17 at 14:22
  • This is a straight python problem, not GIS related. – Midavalo Jul 7 '17 at 14:41

You need to actually write to the file - currently all you're doing is writing to the console using print.

Something like file.write() will write to your log file, or add a function that will write to your log file.

def write_log(text, file):
    f = open(file, 'a')           # 'a' will append to an existing file if it exists
    f.write("{}\n".format(text))  # write the text to the logfile and move to next line

logfile = r"c:\temp\mylogfile.log"  # name of my log file

# Some code here
print "do this!"                # This will only display to the console
write_log("do this!", logfile)  # Write the specified text to the logfile

# Other code here
print "do that"
write_log("do that", logfile)

# Even more code here
print "do something else"
write_log("do something else", logfile)

Not the answer you're looking for? Browse other questions tagged or ask your own question.