feat: implement persistent app logging system with UI history viewer in settings

This commit is contained in:
Jhony Cesar
2026-08-04 16:41:48 -04:00
parent d0356573b9
commit 0d1991337a
9 changed files with 402 additions and 20 deletions

View File

@@ -4,18 +4,20 @@ import android.content.Context
import androidx.room.Database import androidx.room.Database
import androidx.room.Room import androidx.room.Room
import androidx.room.RoomDatabase import androidx.room.RoomDatabase
import com.example.data.model.AppLog
import com.example.data.model.MaintenanceActivity import com.example.data.model.MaintenanceActivity
import com.example.data.model.OSUpdateHistory import com.example.data.model.OSUpdateHistory
import com.example.data.model.SyncConflictLog import com.example.data.model.SyncConflictLog
import com.example.data.model.UserAccess import com.example.data.model.UserAccess
@Database( @Database(
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class], entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class],
version = 5, version = 6,
exportSchema = false exportSchema = false
) )
abstract class AppDatabase : RoomDatabase() { abstract class AppDatabase : RoomDatabase() {
abstract fun maintenanceDao(): MaintenanceDao abstract fun maintenanceDao(): MaintenanceDao
abstract fun appLogDao(): AppLogDao
companion object { companion object {
@Volatile @Volatile

View File

@@ -0,0 +1,23 @@
package com.example.data.local
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.data.model.AppLog
import kotlinx.coroutines.flow.Flow
@Dao
interface AppLogDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertLog(log: AppLog)
@Query("SELECT * FROM app_logs ORDER BY timestamp DESC LIMIT 500")
fun getAllLogsFlow(): Flow<List<AppLog>>
@Query("SELECT * FROM app_logs ORDER BY timestamp DESC LIMIT 500")
suspend fun getAllLogsList(): List<AppLog>
@Query("DELETE FROM app_logs")
suspend fun clearAllLogs()
}

View File

@@ -0,0 +1,23 @@
package com.example.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Entity(tableName = "app_logs")
data class AppLog(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val timestamp: Long = System.currentTimeMillis(),
val level: String, // "ERROR", "WARN", "INFO"
val tag: String,
val message: String,
val stackTrace: String? = null
) {
val formattedTimestamp: String
get() {
val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
return sdf.format(Date(timestamp))
}
}

View File

@@ -75,16 +75,26 @@ class GoogleDriveSyncService(
?: throw IOException("Falha ao obter token de acesso para a Google Drive API.") ?: throw IOException("Falha ao obter token de acesso para a Google Drive API.")
} }
private val appLogger = com.example.util.AppLogger.getInstance(context)
/** /**
* Uploads a photo file to Google Drive in the specified folder. * Uploads a photo file to Google Drive in the specified folder.
* Sets public read permission and returns the DriveUploadResult containing webViewLink and fileId. * Sets public read permission and returns the DriveUploadResult containing webViewLink and fileId.
*/ */
fun uploadPhotoToDrive(photoFile: File, osNumber: String): DriveUploadResult { fun uploadPhotoToDrive(photoFile: File, osNumber: String): DriveUploadResult {
if (!photoFile.exists()) { if (!photoFile.exists()) {
throw IOException("Arquivo local da foto não existe: ${photoFile.absolutePath}") val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
appLogger.logError(tag, err)
throw IOException(err)
}
val token = try {
getAccessToken()
} catch (e: Exception) {
appLogger.logError(tag, "Falha ao obter token de acesso do Google Drive: ${e.message}", e)
throw e
} }
val token = getAccessToken()
val timestamp = System.currentTimeMillis() val timestamp = System.currentTimeMillis()
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "") val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg" val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
@@ -96,18 +106,16 @@ class GoogleDriveSyncService(
} }
""".trimIndent() """.trimIndent()
val multipartRelatedType = "multipart/related".toMediaType()
val multipartBody = MultipartBody.Builder() val multipartBody = MultipartBody.Builder()
.setType(MultipartBody.FORM) .setType(multipartRelatedType)
.addPart( .addPart(
metadataJson.toRequestBody("application/json; charset=UTF-8".toMediaType()) metadataJson.toRequestBody("application/json; charset=UTF-8".toMediaType())
) )
.addPart( .addPart(
MultipartBody.Part.createFormData(
"file",
fileName,
photoFile.asRequestBody("image/jpeg".toMediaType()) photoFile.asRequestBody("image/jpeg".toMediaType())
) )
)
.build() .build()
val uploadRequest = Request.Builder() val uploadRequest = Request.Builder()
@@ -116,30 +124,44 @@ class GoogleDriveSyncService(
.post(multipartBody) .post(multipartBody)
.build() .build()
val response = client.newCall(uploadRequest).execute() val response = try {
client.newCall(uploadRequest).execute()
} catch (e: Exception) {
appLogger.logError(tag, "Erro de conexão ao enviar foto da OS $osNumber para o Drive: ${e.message}", e)
throw e
}
val responseBody = response.body?.string() val responseBody = response.body?.string()
if (!response.isSuccessful || responseBody.isNullOrBlank()) { if (!response.isSuccessful || responseBody.isNullOrBlank()) {
val errorMsg = "Erro no upload para o Google Drive: HTTP ${response.code} - $responseBody" val errorMsg = "Erro no upload da OS $osNumber para o Google Drive: HTTP ${response.code} - $responseBody"
Log.e(tag, errorMsg) appLogger.logError(tag, errorMsg)
throw IOException(errorMsg) throw IOException(errorMsg)
} }
val adapter = moshi.adapter(DriveFileResponse::class.java) val adapter = moshi.adapter(DriveFileResponse::class.java)
val driveFile = adapter.fromJson(responseBody) val driveFile = adapter.fromJson(responseBody)
?: throw IOException("Resposta inválida da API do Google Drive ao criar arquivo.") ?: run {
val msg = "Resposta inválida da API do Google Drive ao criar arquivo da OS $osNumber."
appLogger.logError(tag, msg)
throw IOException(msg)
}
val fileId = driveFile.id ?: throw IOException("Id do arquivo não retornado pelo Google Drive.") val fileId = driveFile.id ?: run {
val msg = "Id do arquivo não retornado pelo Google Drive para a OS $osNumber."
appLogger.logError(tag, msg)
throw IOException(msg)
}
// Make file publicly viewable // Make file publicly viewable
try { try {
setFilePublicPermission(fileId, token) setFilePublicPermission(fileId, token)
} catch (e: Exception) { } catch (e: Exception) {
Log.w(tag, "Falha ao definir permissão pública do arquivo $fileId: ${e.message}") appLogger.logWarning(tag, "Falha ao definir permissão pública do arquivo $fileId: ${e.message}")
} }
val directViewUrl = "https://lh3.googleusercontent.com/d/$fileId" val directViewUrl = "https://lh3.googleusercontent.com/d/$fileId"
Log.d(tag, "Foto enviada com sucesso para o Drive. File ID: $fileId, Link: $directViewUrl") appLogger.logInfo(tag, "Foto enviada com sucesso para o Drive. OS: $osNumber, File ID: $fileId")
return DriveUploadResult( return DriveUploadResult(
fileId = fileId, fileId = fileId,

View File

@@ -21,9 +21,17 @@ class MaintenanceRepository(
val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager() val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager()
) { ) {
private val appDatabase = com.example.data.local.AppDatabase.getDatabase(context)
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager) private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager)
private val driveSyncService = com.example.data.remote.GoogleDriveSyncService(context) private val driveSyncService = com.example.data.remote.GoogleDriveSyncService(context)
private val networkMonitor = com.example.util.NetworkMonitor(context) private val networkMonitor = com.example.util.NetworkMonitor(context)
private val appLogDao = appDatabase.appLogDao()
val allAppLogs: Flow<List<com.example.data.model.AppLog>> = appLogDao.getAllLogsFlow()
suspend fun clearAppLogs() = withContext(Dispatchers.IO) {
appLogDao.clearAllLogs()
}
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected() fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()

View File

@@ -1,6 +1,7 @@
package com.example.ui.screens package com.example.ui.screens
import android.widget.Toast import android.widget.Toast
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
@@ -63,9 +64,11 @@ fun SettingsScreen(
val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle() val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle()
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle() val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle() val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
var showClearCacheDialog by remember { mutableStateOf(false) } var showClearCacheDialog by remember { mutableStateOf(false) }
var showConflictsDialog by remember { mutableStateOf(false) } var showConflictsDialog by remember { mutableStateOf(false) }
var showLogsDialog by remember { mutableStateOf(false) }
var activeTestModal by remember { mutableStateOf<Int?>(null) } var activeTestModal by remember { mutableStateOf<Int?>(null) }
// Start monitoring GCP API status when screen is open, stop when closed // Start monitoring GCP API status when screen is open, stop when closed
@@ -364,6 +367,15 @@ fun SettingsScreen(
showConflictsDialog = true showConflictsDialog = true
} }
) )
// Botão 5: Histórico de Logs do App
AdminButton(
text = "Histórico de Logs",
icon = Icons.Default.ListAlt,
onClick = {
showLogsDialog = true
}
)
} }
} }
} }
@@ -416,6 +428,14 @@ fun SettingsScreen(
onDismiss = { showConflictsDialog = false } onDismiss = { showConflictsDialog = false }
) )
} }
if (showLogsDialog) {
AppLogsHistoryDialog(
logs = appLogs,
onClear = { viewModel.clearAppLogs() },
onDismiss = { showLogsDialog = false }
)
}
} }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@@ -740,4 +760,189 @@ fun AdminButton(
} }
} }
@Composable
fun AppLogsHistoryDialog(
logs: List<com.example.data.model.AppLog>,
onClear: () -> Unit,
onDismiss: () -> Unit
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Card(
modifier = Modifier
.fillMaxWidth(0.92f)
.fillMaxHeight(0.85f),
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = Color.White)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
// Header
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.ListAlt,
contentDescription = "Logs",
tint = BrandGreen
)
Text(
text = "Histórico de Logs do App",
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
color = BrandBlack
)
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Fechar")
}
}
Spacer(modifier = Modifier.height(8.dp))
// Subtitle
Text(
text = "Falhas, avisos de sincronização e logs de execução. É possível selecionar e copiar qualquer trecho de texto.",
fontSize = 12.sp,
color = Color.Gray
)
Spacer(modifier = Modifier.height(12.dp))
// SelectionContainer wrapping the LazyColumn for selectable text!
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.background(Color(0xFFF8F9FA), shape = RoundedCornerShape(8.dp))
.padding(8.dp)
) {
if (logs.isEmpty()) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = "Nenhum log registrado até o momento.",
color = Color.Gray,
fontSize = 13.sp
)
}
} else {
SelectionContainer {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(logs) { log ->
Card(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(6.dp),
colors = CardDefaults.cardColors(containerColor = Color.White),
border = BorderStroke(
1.dp,
when (log.level) {
"ERROR" -> Color(0xFFFFCDD2)
"WARN" -> Color(0xFFFFE0B2)
else -> Color(0xFFE0E0E0)
}
)
) {
Column(modifier = Modifier.padding(10.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Surface(
color = when (log.level) {
"ERROR" -> Color(0xFFD32F2F)
"WARN" -> Color(0xFFF57C00)
else -> BrandGreen
},
shape = RoundedCornerShape(4.dp)
) {
Text(
text = "[${log.level}] ${log.tag}",
color = Color.White,
fontSize = 10.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
Text(
text = log.formattedTimestamp,
fontSize = 10.sp,
color = Color.Gray
)
}
Spacer(modifier = Modifier.height(6.dp))
Text(
text = log.message,
fontSize = 12.sp,
fontWeight = FontWeight.Medium,
color = BrandBlack
)
if (!log.stackTrace.isNullOrBlank()) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = log.stackTrace,
fontSize = 10.sp,
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
color = Color(0xFFC62828)
)
}
}
}
}
}
}
}
}
Spacer(modifier = Modifier.height(12.dp))
// Footer
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(
onClick = onClear,
enabled = logs.isNotEmpty()
) {
Icon(Icons.Default.Delete, contentDescription = "Limpar", modifier = Modifier.size(16.dp), tint = Color.Red)
Spacer(modifier = Modifier.width(4.dp))
Text("Limpar Histórico", color = Color.Red, fontSize = 12.sp)
}
Button(
onClick = onDismiss,
colors = ButtonDefaults.buttonColors(containerColor = BrandGreen)
) {
Text("Fechar", fontWeight = FontWeight.Bold)
}
}
}
}
}
}

View File

@@ -96,6 +96,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
initialValue = emptyList() initialValue = emptyList()
) )
val appLogsState: StateFlow<List<com.example.data.model.AppLog>> = repository.allAppLogs
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
fun clearAppLogs() {
viewModelScope.launch {
repository.clearAppLogs()
}
}
val analyticsState: StateFlow<AnalyticsState> = combine( val analyticsState: StateFlow<AnalyticsState> = combine(
repository.allActivities, repository.allActivities,
repository.allHistory repository.allHistory

View File

@@ -0,0 +1,82 @@
package com.example.util
import android.content.Context
import android.util.Log
import com.example.data.local.AppDatabase
import com.example.data.model.AppLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AppLogger private constructor(context: Context) {
private val db = AppDatabase.getDatabase(context)
private val appLogDao = db.appLogDao()
private val scope = CoroutineScope(Dispatchers.IO)
fun logError(tag: String, message: String, throwable: Throwable? = null) {
Log.e(tag, message, throwable)
val stackTrace = throwable?.stackTraceToString()
scope.launch {
try {
appLogDao.insertLog(
AppLog(
level = "ERROR",
tag = tag,
message = message,
stackTrace = stackTrace
)
)
} catch (e: Exception) {
Log.e("AppLogger", "Falha ao gravar log no Room", e)
}
}
}
fun logWarning(tag: String, message: String) {
Log.w(tag, message)
scope.launch {
try {
appLogDao.insertLog(
AppLog(
level = "WARN",
tag = tag,
message = message
)
)
} catch (e: Exception) {
Log.e("AppLogger", "Falha ao gravar log no Room", e)
}
}
}
fun logInfo(tag: String, message: String) {
Log.i(tag, message)
scope.launch {
try {
appLogDao.insertLog(
AppLog(
level = "INFO",
tag = tag,
message = message
)
)
} catch (e: Exception) {
Log.e("AppLogger", "Falha ao gravar log no Room", e)
}
}
}
companion object {
@Volatile
private var INSTANCE: AppLogger? = null
fun getInstance(context: Context): AppLogger {
return INSTANCE ?: synchronized(this) {
val instance = AppLogger(context.applicationContext)
INSTANCE = instance
instance
}
}
}
}

View File

@@ -169,9 +169,13 @@ A gestão e armazenamento de arquivos de mídia (fotos das ordens de serviço)
* **Estratégia Offline-First & Múltiplas Fotos:** As fotos capturadas/selecionadas são salvas em armazenamento local privado (`filesDir/os_photos/`). O aplicativo suporta o anexo de **múltiplas fotos por atualização**, armazenando os caminhos/URLs concatenados pelo delimitador `|` (ex: `url1|url2|url3`), garantindo compatibilidade total com a Room DB e o Google Sheets. Durante a sincronização, o app realiza o upload multipart HTTP POST de cada foto para o Drive, ajusta as permissões do arquivo para leitura pública (`anyone with link`) e obtém as URLs diretas de visualização (`webViewLink`). * **Estratégia Offline-First & Múltiplas Fotos:** As fotos capturadas/selecionadas são salvas em armazenamento local privado (`filesDir/os_photos/`). O aplicativo suporta o anexo de **múltiplas fotos por atualização**, armazenando os caminhos/URLs concatenados pelo delimitador `|` (ex: `url1|url2|url3`), garantindo compatibilidade total com a Room DB e o Google Sheets. Durante a sincronização, o app realiza o upload multipart HTTP POST de cada foto para o Drive, ajusta as permissões do arquivo para leitura pública (`anyone with link`) e obtém as URLs diretas de visualização (`webViewLink`).
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto não remove o arquivo da pasta remota no Google Drive. A API do Drive executa uma requisição `PATCH` alterando o nome do arquivo para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), enquanto a aplicação remove o vínculo do registro ativo no banco de dados local e na planilha. * **Regra de Exclusão (Soft Delete):** A exclusão de uma foto não remove o arquivo da pasta remota no Google Drive. A API do Drive executa uma requisição `PATCH` alterando o nome do arquivo para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), enquanto a aplicação remove o vínculo do registro ativo no banco de dados local e na planilha.
* Guarda o log sequencial de alterações feitas por todos os inspetores. ### 4.4. Sistema de Registro e Histórico de Logs (`AppLogger.kt`)
* Colunas configuradas: `id`, `numeroOs`, `timestamp`, `percentualAnterior`, `percentualNovo`, `observacao`, `fotoPath`, `responsavel`, `email_editor`.
* Possui funcionalidade de **Self-Healing** (Auto-reparação): se a coluna `email_editor` não for encontrada no carregamento da planilha física, o app executa uma chamada PUT automática para inseri-la no cabeçalho na coluna correspondente. O aplicativo dispõe de um subsistema de auditoria e diagnóstico local para registro de falhas, erros de rede, problemas no Google Drive/Sheets e avisos de sincronização:
* **Tabela Room DB (`app_logs`):** Armazena os eventos com `timestamp`, `level` (`ERROR`, `WARN`, `INFO`), `tag`, `message` e `stackTrace`.
* **Utilitário `AppLogger.kt`:** Gerencia a gravação assíncrona thread-safe no banco local e emissão no Logcat.
* **Interface de Diagnóstico (`SettingsScreen.kt`):** Botão **"Histórico de Logs"** exibe os logs em um modal dialog envolvido por `SelectionContainer` do Jetpack Compose, permitindo a seleção e cópia de textos pelo usuário.
--- ---