feat: implement persistent app logging system with UI history viewer in settings
This commit is contained in:
@@ -4,18 +4,20 @@ import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import com.example.data.model.AppLog
|
||||
import com.example.data.model.MaintenanceActivity
|
||||
import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.UserAccess
|
||||
|
||||
@Database(
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class],
|
||||
version = 5,
|
||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class],
|
||||
version = 6,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun maintenanceDao(): MaintenanceDao
|
||||
abstract fun appLogDao(): AppLogDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
|
||||
23
app/src/main/java/com/example/data/local/AppLogDao.kt
Normal file
23
app/src/main/java/com/example/data/local/AppLogDao.kt
Normal 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()
|
||||
}
|
||||
23
app/src/main/java/com/example/data/model/AppLog.kt
Normal file
23
app/src/main/java/com/example/data/model/AppLog.kt
Normal 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))
|
||||
}
|
||||
}
|
||||
@@ -75,16 +75,26 @@ class GoogleDriveSyncService(
|
||||
?: 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.
|
||||
* Sets public read permission and returns the DriveUploadResult containing webViewLink and fileId.
|
||||
*/
|
||||
fun uploadPhotoToDrive(photoFile: File, osNumber: String): DriveUploadResult {
|
||||
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 sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
||||
@@ -96,17 +106,15 @@ class GoogleDriveSyncService(
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val multipartRelatedType = "multipart/related".toMediaType()
|
||||
|
||||
val multipartBody = MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.setType(multipartRelatedType)
|
||||
.addPart(
|
||||
metadataJson.toRequestBody("application/json; charset=UTF-8".toMediaType())
|
||||
)
|
||||
.addPart(
|
||||
MultipartBody.Part.createFormData(
|
||||
"file",
|
||||
fileName,
|
||||
photoFile.asRequestBody("image/jpeg".toMediaType())
|
||||
)
|
||||
photoFile.asRequestBody("image/jpeg".toMediaType())
|
||||
)
|
||||
.build()
|
||||
|
||||
@@ -116,30 +124,44 @@ class GoogleDriveSyncService(
|
||||
.post(multipartBody)
|
||||
.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()
|
||||
|
||||
if (!response.isSuccessful || responseBody.isNullOrBlank()) {
|
||||
val errorMsg = "Erro no upload para o Google Drive: HTTP ${response.code} - $responseBody"
|
||||
Log.e(tag, errorMsg)
|
||||
val errorMsg = "Erro no upload da OS $osNumber para o Google Drive: HTTP ${response.code} - $responseBody"
|
||||
appLogger.logError(tag, errorMsg)
|
||||
throw IOException(errorMsg)
|
||||
}
|
||||
|
||||
val adapter = moshi.adapter(DriveFileResponse::class.java)
|
||||
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
|
||||
try {
|
||||
setFilePublicPermission(fileId, token)
|
||||
} 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"
|
||||
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(
|
||||
fileId = fileId,
|
||||
|
||||
@@ -21,9 +21,17 @@ class MaintenanceRepository(
|
||||
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 driveSyncService = com.example.data.remote.GoogleDriveSyncService(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
|
||||
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.example.ui.screens
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -63,9 +64,11 @@ fun SettingsScreen(
|
||||
val connectionTested by viewModel.connectionTested.collectAsStateWithLifecycle()
|
||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
|
||||
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
||||
|
||||
var showClearCacheDialog by remember { mutableStateOf(false) }
|
||||
var showConflictsDialog by remember { mutableStateOf(false) }
|
||||
var showLogsDialog by remember { mutableStateOf(false) }
|
||||
var activeTestModal by remember { mutableStateOf<Int?>(null) }
|
||||
|
||||
// Start monitoring GCP API status when screen is open, stop when closed
|
||||
@@ -364,6 +367,15 @@ fun SettingsScreen(
|
||||
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 }
|
||||
)
|
||||
}
|
||||
|
||||
if (showLogsDialog) {
|
||||
AppLogsHistoryDialog(
|
||||
logs = appLogs,
|
||||
onClear = { viewModel.clearAppLogs() },
|
||||
onDismiss = { showLogsDialog = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -96,6 +96,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
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(
|
||||
repository.allActivities,
|
||||
repository.allHistory
|
||||
|
||||
82
app/src/main/java/com/example/util/AppLogger.kt
Normal file
82
app/src/main/java/com/example/util/AppLogger.kt
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user