Logging database changes in lift-mapper

Here is a little trick to log the changed properties
on the lift-mapper objets.

  • First we define a changeLogger trait that extends Mapper

    trait ChangeLogger[T <: Mapper[T] ] {
        def checkChanges(obj: T): Unit = {
            if (obj.dirty_?) {
                Log.debug("Object " + obj.getSingleton.dbTableName + " has changed")
                obj.formFields.foreach(f => {
                    f.dirty_? match {
                        case true => Log.debug(" ---> Property %s was='%s' and now is = '%s'".format(f.name, f.is.toString, f.was.toString))

  • Extend LongKeyedMetaMapper (or any other MetaMapper class) to call ChangeLogger checkChanges method after save (or after delete …)

    trait ChangeLoggerMetaMapper[T <: LongKeyedMapper[T]] extends LongKeyedMetaMapper[T]
                                                    with ChangeLogger[T] { self : T =>
        override def afterSave: List[(T) => Unit] = checkChanges _ :: super.afterSave
  • Model object

    class Item extends LongKeyedMapper[Item] with IdPK
                                             with ChangeLogger[Item] {
        def getSingleton = Item
        object name extends MappedString(this, 100) {
            override def validations = valMinLen(1, "Must be not empty") _ ::
                                       valUnique("Name must be unique") _ ::
    object Item extends Item with ChangeLoggerMetaMapper[Item] {
        def findByName(name: String): List[Item] = {
            Item.findAll(By(Item.name, name))

The code can be found on http://github.com/jgoday/sample_lift_testing

Documentation for lift-mapper (version lift-1.1-M6) http://scala-tools.org/mvnsites/liftweb-1.1-M6/lift-mapper/scaladocs/index.html

    • Svem
    • May 16th, 2010

    Very nice post, thank you for making it, might I ask how do you make the logging scheme save? Your example does not show this, I have been to the wiki page and it is confusing.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: