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 ?
What you need is to create (if it doesn't exist yet) a startup.py
file in the QGIS python folder:
/home/YOUR_USER/.qgis2/python/
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:
---- 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)