It would be possible to do this in the script if you autopilot hardware supports Lua scripting. If not, here is a thread with examples for using the mavlink library with arduino. I’m not sure of a way to write data to a dataflash log using mavlink. It might be possible.