2

i would like to log every layers openings in PyQGIS, regardless of the opened project.

Is there a way to achieve that ?

Where should be the Python code be located in that case ?

6

What you need is to create (if it doesn't exist yet) a startup.py file in the QGIS python folder:

  • On GNU/Linux: /home/YOUR_USER/.qgis2/python/
  • On Windows: (User folder)/.qgis2/python/ Not sure about it, please tell me if you find it to update the answer

and write inside that file something like this:

from qgis.core import QgsMapLayerRegistry

def myLog(layers):
  f=open('/tmp/log.txt','a') # Change this path to your own file
  for lyr in layers:
    f.write('Layer added: %s, id: %s, source: %s' % (lyr.name(), lyr.id(), lyr.source()))
  f.close()

QgsMapLayerRegistry.instance().layersAdded.connect(myLog)

Every time you start QGIS, the code is executed, making myLog to listen to any layer opening, as well as to leave some data into /tmp/log.txt Note that the layer id already stores date/time data, but you could also use Python to write such data into the log.txt file.

You would end up with this:

enter image description here

---- EDIT ----

Note: According to the docs, layersAdded is "[...] emitted for layers added to the registry, but not to the legend and canvas." In case that you want to make sure to only add to the log those layers loaded into legend/canvas, you probably would use the legendLayersAdded SIGNAL instead. Just replace the last line of the code snippet above by:

QgsMapLayerRegistry.instance().legendLayersAdded.connect(myLog)
  • wow ... thanks for this thorough answer gcarillo ... i'm gonna try this ... I have just a question about your code : why do u iterate over layers in the loop ? i suppose there's only one layer involved per LayersAdded event ... no ? – snaileater May 18 '15 at 7:15
  • @snaileater When you select and open several layers from dialogs such as 'Add Vector Layer', the layersAdded SIGNAL sends a list of layers, so your SLOT gets triggered only once, rather than one time per layer. – Germán Carrillo May 18 '15 at 14:30
  • BTW, I edited the answer to append some relevant info that might be also interesting for you. – Germán Carrillo May 18 '15 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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