Added logging function, optimized.